tags:

views:

2661

answers:

5

I have a dict where each key references an int value. What's the best way to sort the keys into a list depending on the values?

+15  A: 
>>> mydict = {'a':1,'b':3,'c':2}
>>> sorted(mydict, key=lambda key: mydict[key])
['a', 'c', 'b']
MizardX
thanks, Brian R. Body. :)
MizardX
Bondy* ... can't spell tody
MizardX
+4  A: 
list = sorted(dict.items(), key=lambda x: x[1])
Jonas Kölker
A: 
[v[0] for v in sorted(foo.items(), key=lambda(k,v): (v,k))]
Can Berk Güder
+40  A: 

I like this one:

sorted(d, key=d.get)
dF
This is really the most elegant.
Kiv
Too bad I haven't waited with the accept. +1
Richard J. Terrell
A: 

odict might work for you.

thompsongunner