Sorting a python dict by value

12 Nov 2007

SEE UPDATED VERSION.

09-Sept-2008. It works, but there is a better way that is faster.


Don't search for "python dict sort by value" since you'll get outdated answers. As of python 2.4, the "right" way to do this is:

alist = sorted(adict.iteritems(), key=lambda (k,v): (v,k))

to get the reverse order, add on a ,reverse=True

This is the fastest way to do this and it uses the least amount of memory. Enjoy.

>>> adict = {'first':1, 'second':2,'third':3, 'fourth': 4}
>>> adict
{'second': 2, 'fourth': 4, 'third': 3, 'first': 1}
>>> sorted(adict.iteritems(), key=lambda (k,v):(v,k))
[('first', 1), ('second', 2), ('third', 3), ('fourth', 4)]
>>> sorted(adict.iteritems(), key=lambda (k,v):(v,k), reverse=True)
[('fourth', 4), ('third', 3), ('second', 2), ('first', 1)]

Comment 2008-06-29 by None

Wow, this was a golden post. Thanks!


Comment 2008-08-28 by None

excellent


Comment 2008-08-30 by None

I think that PEP 265 has some relevance to your claims here. I did a few tests a well, posted at http://writeonly.wordpress.com/2008/08/30/sorting-dictionaries-by-value-in-python-improved/, and I think this is not the quickest sort by value implementation.

I hope you'll prove me wrong!

gL


Comment 2008-08-30 by None

Hi "writeonly" -- your work looks very interesting! I'll look into this later in the weekend. --nickg


Comment 2008-09-08 by None

many more ways to do it here with some benchmarks in the comments:

http://coreygoldberg.blogspot.com/2008/06/python-sort-dictionary-by-values.html


Comment 2009-01-06 by None

ok. that worked great except that it didn't sort numerican values correctly.
So things ended up being sorted as
0.12
2.3
22.4
3
4
..
..


Comment 2009-03-31 by None

I love you.
That was exactly what I was looking for!


Comment 2009-10-17 by None

Anonymous... because you stored them as strings