139
votes

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?

4
Also, this asks about sorting by key, the linked answer is about sorting by value. - ForeverWintr

4 Answers

103
votes
>>> mydict = {'a':1,'b':3,'c':2}
>>> sorted(mydict, key=lambda key: mydict[key])
['a', 'c', 'b']
353
votes

I like this one:

sorted(d, key=d.get)
16
votes
my_list = sorted(dict.items(), key=lambda x: x[1])
3
votes
[v[0] for v in sorted(foo.items(), key=lambda(k,v): (v,k))]