The Python Oracle

How do I sort a list of dictionaries by a value of the dictionary?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Melt

--

Chapters
00:00 Question
00:28 Accepted answer (Score 3457)
00:59 Answer 2 (Score 231)
01:21 Answer 3 (Score 110)
01:52 Answer 4 (Score 74)
02:25 Thank you

--

Full question
https://stackoverflow.com/questions/7289...

Accepted answer links:
[sorted()]: https://docs.python.org/library/function...
[operator.itemgetter]: https://docs.python.org/library/operator...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list #sorting #dictionary #datastructures

#avk47



ACCEPTED ANSWER

Score 3695


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)



ANSWER 2

Score 247


import operator

To sort the list of dictionaries by key='name':

list_of_dicts.sort(key=operator.itemgetter('name'))

To sort the list of dictionaries by key='age':

list_of_dicts.sort(key=operator.itemgetter('age'))



ANSWER 3

Score 123


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

my_list.sort(lambda x,y : cmp(x['name'], y['name']))

my_list will now be what you want.

Or better:

Since Python 2.4, there's a key argument is both more efficient and neater:

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

...the lambda is, IMO, easier to understand than operator.itemgetter, but your mileage may vary.




ANSWER 4

Score 75


If you want to sort the list by multiple keys, you can do the following:

my_list = [{'name':'Homer', 'age':39}, {'name':'Milhouse', 'age':10}, {'name':'Bart', 'age':10} ]
sortedlist = sorted(my_list , key=lambda elem: "%02d %s" % (elem['age'], elem['name']))

It is rather hackish, since it relies on converting the values into a single string representation for comparison, but it works as expected for numbers including negative ones (although you will need to format your string appropriately with zero paddings if you are using numbers).