-3

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?

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Wells
  • 10,415
  • 14
  • 55
  • 85

2 Answers2

5
>>> 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())
jme
  • 19,895
  • 6
  • 41
  • 39
5

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.

Wells
  • 10,415
  • 14
  • 55
  • 85