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))
Post a Comment