Sorting dictionary keys in python

PythonSorting

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

I like this one:

sorted(d, key=d.get)

Solution 2 - Python

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

Solution 3 - Python

my_list = sorted(dict.items(), key=lambda x: x[1])

Solution 4 - Python

[v[0] for v in sorted(foo.items(), key=lambda(k,v): (v,k))]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGeorgeView Question on Stackoverflow
Solution 1 - PythondF.View Answer on Stackoverflow
Solution 2 - PythonMarkus JarderotView Answer on Stackoverflow
Solution 3 - PythonJonas KölkerView Answer on Stackoverflow
Solution 4 - PythonCan Berk GüderView Answer on Stackoverflow