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

ID : 318

viewed : 178

Tags : pythonlistsortingdictionarydata-structurespython





Top 5 Answer for python - How do I sort a list of dictionaries by a value of the dictionary?

vote vote

97

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) 
vote vote

86

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')) 
vote vote

78

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.

vote vote

62

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).

vote vote

56

a = [{'name':'Homer', 'age':39}, ...]  # This changes the list a a.sort(key=lambda k : k['name'])  # This returns a new list (a is not modified) sorted(a, key=lambda k : k['name'])  

Top 3 video Explaining python - How do I sort a list of dictionaries by a value of the dictionary?







Related QUESTION?