Sorting an Array of Dictionaries by key

October 5, 2012

I had an array of dictionaries in Python, and wanted to sort by one element of the dictionary.

So, given:

lToSort = [
    {'name':'Delbert'},
    {'name':'Becky'},
    {'name':'Albert'},
    {'name':'Chris'},
]

I wanted to get back:

lSorted = [
    {'name':'Albert'},
    {'name':'Becky'},
    {'name':'Chris'},
    {'name':'Delbert'},
]

You can do this simply in Python:

from operator import itemgetter
lSorted = sorted(lToSort, key=itemgetter('name'))