I have this:
{1: 'Foo', 2: 'Bar', 3: 'Chazz', 4: 'Alpha', 6: 'Zorn', 7: 'Doe'}
And I want a list of the keys in the dict sorted alphabetically by the values:
[4,2,3,7,1,6]
What's the simplest, most pythonic approach that works in 2.7?
>>> d = {1: 'Foo', 2: 'Bar', 3: 'Chazz', 4: 'Alpha', 6: 'Zorn', 7: 'Doe'}
>>> sorted(d, key=d.get)
[4, 2, 3, 7, 1, 6]
Note that this is case sensitive. For example, if "Bar"
were instead "bar"
, the result of the above would have 2
at the very end of the list. In this case, you might want:
sorted(d, key=lambda x: d[x].lower())
Well, this works just fine. not sure if there's a better/more pythonic way:
sorted_list = sorted(a, key=a.get)
Where a
is the dict.