June 27, 2008

Python - Sort A Dictionary By Values

Python dictionaries are unordered, but you can extract the keys and values and sort them yourself in a list.

lets say you have this dictionary:
{'a': 2, 
 'b': 4, 
 'c': 3,
 'd': 1}
.. and you want to convert it into a list, sorted by value (not key), like this:
[('d', 1), 
 ('a', 2), 
 ('c', 3), 
 ('b', 4)]
There is a Python Recipe for it with various implementations discussed in the comments.

My favorite one is this:
sorted(foo.items(), key=lambda(k,v):(v,k))

6 comments:

brentp said...

you can also do:
sorted(a.items(), key=lambda (k,v): v)

or use operator:
sorted(a.items(),key=operator.itemgetter(1))

Anonymous said...

>>> x = { 'a':2, 'b':4, 'c':3, 'd':1 }
>>> from operator import itemgetter
>>> sorted(x.iteritems(), key=itemgetter(1))
[('d', 1), ('a', 2), ('c', 3), ('b', 4)]

This is nicer IMHO. You should almost always use iteritems() instead of items(), and itemgetter() is a nicer way to extract what you need to sort on without the ugly lambda.

Jeremy Kloth said...

if you are just interest in having the keys in sorted order, you can also use:
sorted(a, key=a.__getitem__)

Paddy3118 said...

Corey,
Your example:
sorted(foo.items(), key=lambda(k,v):(v,k))
sorts primarily on values, but if they are the same, will then sort on keys. This is not equivalent to a plain sort on values.

- Paddy.

Anonymous said...

To follow up on what "anonymous" said, I tested these methods (lambdas, iteritems, etc) for runtime, and the itemgetter method seems to be fastest for python 2.4, at least. YMMV of course... Cheers, Gregg

http://writeonly.wordpress.com/2008/08/30/sorting-dictionaries-by-value-in-python-improved/

BigVig said...

Jeremy: thanks, exactly what I was looking for. None of the other solutions actually return a sorted dict, but convert it to a list sorted tuples. Right?