Sorting dictionary keys in python [duplicate]

2019-01-07 03:11发布

问题:

This question already has an answer here:

  • How do I sort a dictionary by value? 41 answers

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:

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


回答2:

I like this one:

sorted(d, key=d.get)


回答3:

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


回答4:

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