Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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

2 Answers

kshitijrana14
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)
pankajshivnani123
#The sorted() function takes a key= parameter
newlist = sorted(list_to_be_sorted, key=lambda k: k['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'))
sandhya6gczb
Use the key argument to sort the dictionary by value.
For example

my_list = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
my_list = sorted(my_list, key=lambda k: k['name'])

Login / Signup to Answer the Question.