Possible Duplicate:
Python: Sort a dictionary by value
d = {"a":4, "b":12, "c":2}
If I use sorted() with lambda:
s = sorted(d.items(), key=lambda(k,v):(v,k))
I get a list tuples (key,value) but I want a dict again:
{"c":2, "a":4, "b":12}
And doing dict(the_list_of_tuples)
you're back to square one.
Standard dict
objects are not sorted and so do not guarantee or preserve any ordering. This is because since you usually use a dict by get a value for a key ordering is unimportant.
If you want to preserve ordering you can use an OrderedDict
. This isn't sorted but does remember the order in which items are added to it. So you can create one using your key value pairs in sorted order:
>>> d = {"a":4, "b":12, "c":2}
>>> from collections import OrderedDict
>>> od = OrderedDict(sorted(d.items(), key=lambda(k,v):(v,k)))
>>> od
OrderedDict([('c', 2), ('a', 4), ('b', 12)])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With