Noteworthy
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)]
from http://blog.modp.com/2007/11/sorting-python-dict-by-value.html