Sorting dictionary keys in python

Question:

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?

Asked By: George

||

Answers:

>>> mydict = {'a':1,'b':3,'c':2}
>>> sorted(mydict, key=lambda key: mydict[key])
['a', 'c', 'b']
Answered By: Markus Jarderot
my_list = sorted(dict.items(), key=lambda x: x[1])
Answered By: Jonas Kölker
[v[0] for v in sorted(foo.items(), key=lambda(k,v): (v,k))]
Answered By: Can Berk Güder

I like this one:

sorted(d, key=d.get)
Answered By: dF.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.