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?

1
125
2/24/2009 12:11:52 AM

Accepted Answer

>>> mydict = {'a':1,'b':3,'c':2}
>>> sorted(mydict, key=lambda key: mydict[key])
['a', 'c', 'b']
97
10/20/2010 12:23:35 PM

I like this one:

sorted(d, key=d.get)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon