Python - Sort A Dictionary By Values
Python - Sort A Dictionary By Values
Submitted by noreply@blogger.com (Corey Goldberg) on Fri, 27/06/2008 - 16:16.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:
My favorite one is this:
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))
