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

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


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 itemgetternewlist = sorted(list_to_be_sorted, key=itemgetter('name')) 

For completeness, add reverse=True to sort in descending order

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


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


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.


matomo