Python – How to sort a list of dictionaries by a value of the dictionary


I have a list of dictionaries and want each item to be sorted by a specific value.

Take into consideration the list:

[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]

When sorted by name, it should become:

[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]

Best Solution

The sorted() function takes a key= parameter

newlist = sorted(list_to_be_sorted, key=lambda d: d['name']) 

Alternatively, you can use operator.itemgetter instead of defining the function yourself

from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name')) 

For completeness, add reverse=True to sort in descending order

newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)