Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort dict by value and return dict, not list of tuples [duplicate]

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.

like image 251
userBG Avatar asked Feb 27 '12 05:02

userBG


1 Answers

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)])
like image 89
Dave Webb Avatar answered Sep 22 '22 18:09

Dave Webb