0

I have a dictionary say:

Red : 2
Blue : 1
Yellow : 9
Black : 9
White : 5

I need to generate a list of keys sorted by the values:

[Blue, Red, White, Black, Yellow]

Is there a neatish way of doing this?

I have had a look around, and there are similar questions, but they all seem to be sorting values or keys only.

Marko
  • 570
  • 5
  • 21
  • For what it's worth, I don't consider the question marked "duplicate" to be a duplicate at all. Luckily you got a good answer before that happened. – Mark Ransom Nov 19 '14 at 16:31
  • Using the duplicate, you get `[('Blue', 1), ('Red', 2), ('White', 5), ('Black', 9)]`. With `[y for y,_ in sorted(x.items(), key=operator.itemgetter(1))]` you get what you want. – fredtantini Nov 19 '14 at 16:33

1 Answers1

2

You can use sorted function with dict.get as its key :

sorted(your_dictionary.keys(), key=your_dictionary.get)

or as says in comments you can just use :

sorted(your_dictionary, key=your_dictionary.get)

Mazdak
  • 105,000
  • 18
  • 159
  • 188