masi masi - 3 months ago 8
Python Question

How do I sort a list of dictionaries by values of the dictionary in Python?

I got a list of dictionaries and want that to be sorted by a value of that dictionary.

This

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


sorted by name, should become

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

Answer

It may look cleaner using a key instead a cmp:

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

or as J.F.Sebastian and others suggested,

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

For completeness (as pointed out in comments by fitzgeraldsteele), add reverse=True to sort descending

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