Categories
data-structures dictionary list python sorting

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

2530

How do I sort a list of dictionaries by a specific key’s value? Given:

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

When sorted by name, it should become:

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

3

  • 5

    Reading the answer and looking on operator.itemgetter. Can I sort on multiple value in the same process (for example we have [{'name':'Bart', 'age':10, 'note':3},{'name':'Homer','age':10,'note':2},{'name':'Vasile','age':20,'note':3}] And to use: from operator import itemgetter newlist = sorted(old_list, key=itemgetter(-'note','name') EDIT: Tested, and it is working but I don’t know how to make note DESC and name ASC.

    – Claudiu

    May 21, 2020 at 7:13


  • the answer is YES, though i didn’t find syntactic sugar for the asc/desc (probably with a function with asc as default. my example, in the following comment, illustrates all conditions, with -1 being desc:

    – alex

    Jul 11 at 13:53

  • def cmpfun(a, b): for (name, inv) in cmps: res = cmp(a[name], b[name]); if res != 0: return res * inv; return 0; data = [dict(name=’alice’, age=10), dict(name=’baruch’, age=9), dict(name=’alice’, age=11),] all_cmps = [[(‘name’, 1), (‘age’, -1)], [(‘name’, 1), (‘age’, 1)], [(‘name’, -1), (‘age’, 1)],] print ‘data:’, data for cmps in all_cmps: print ‘sort:’, cmps; print sorted(data, cmpfun)

    – alex

    Jul 11 at 15:41

3286

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)

13

  • 50

    Using key is not only cleaner but more effecient too.

    – jfs

    Sep 16, 2008 at 15:03

  • 5

    The fastest way would be to add a newlist.reverse() statement. Otherwise you can define a comparison like cmp=lambda x,y: – cmp(x[‘name’],y[‘name’]).

    – Mario F

    Oct 13, 2009 at 7:14

  • 4

    if the sort value is a number you could say: lambda k: (k[‘age’] * -1) to get a reverse sort

    Nov 20, 2009 at 15:16

  • 3

    This also applies to a list of tuples, if you use itemgetter(i) where i is the index of the tuple element to sort on.

    – radicand

    Jul 11, 2012 at 23:14

  • 56

    itemgetter accepts more than one argument: itemgetter(1,2,3) is a function that return a tuple like obj[1], obj[2], obj[3], so you can use it to do complex sorts.

    – Bakuriu

    Sep 7, 2012 at 17:59

216

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

4

  • 16

    Anyway to combine name and age ? (like in SQL ORDER BY name,age ?)

    Feb 17, 2010 at 13:10


  • 46

    @monojohnny: yes, just have the key return a tuple, key=lambda k: (k['name'], k['age']). (or key=itemgetter('name', 'age')). tuple’s cmp will compare each element in turn. it’s bloody brilliant.

    – Claudiu

    Sep 4, 2013 at 22:21


  • 1

    In the documentation (docs.python.org/2/tutorial/datastructures.html) the optional key argument for list.sort() is not described. Any idea where to find that?

    – TTT

    Feb 21, 2014 at 15:21


  • 2

    @TTT: See the library documentation for list and friends.

    – Kevin

    Feb 19, 2015 at 14:56

104

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.

3

  • what could be done if the key is unknown and keeps changing?I mean list of dicts with just one key and value but the key and value could not be defined as they keep changing.

    – Sam

    Dec 1, 2020 at 14:51

  • 1

    I’d need more of an example to look at. Try submitting a possible solution on the codereview stackexchange and asking if there’s a better way.

    – pjz

    Dec 30, 2020 at 1:02

  • 1

    @Sam if you want to sort by the value of the single key in the dict, even if you don’t know the key, you can do key=lambda k: list(k.values())[0]

    – pjz

    Mar 10, 2021 at 6:38