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}]
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)