7

I have a dict {'a': 2, 'b': 0, 'c': 1}.

Need to sort keys by values so that I can get a list ['b', 'c', 'a']

Is there any easy way to do this?

georg
  • 211,518
  • 52
  • 313
  • 390
delsin
  • 313
  • 4
  • 12
  • 2
    Possible duplicate of [Sort a Python dictionary by value](http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value) – zondo May 17 '16 at 10:59

5 Answers5

8
sorted_keys = sorted(my_dict, key=my_dict.get)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
georg
  • 211,518
  • 52
  • 313
  • 390
3
>>> d={'a': 2, 'b': 0, 'c': 1}
>>> [i[0] for i in sorted(d.items(), key=lambda x:x[1])]
['b', 'c', 'a']
riteshtch
  • 8,629
  • 4
  • 25
  • 38
2

try this:

import operator
lst1 = sorted(lst.items(), key=operator.itemgetter(1))
Priyansh Goel
  • 2,660
  • 1
  • 13
  • 37
1

There's a simple way to do it. You can use .items() to get key-value and use sorted to sort them accordingly.

dictionary = sorted(dictionary.items(),key=lambda x:x[1])
Benji
  • 137
  • 3
  • 15
0
>>> d = {'a':2, 'b':0, 'c':1}
>>> sor = sorted(d.items(), key=lambda x: x[1])
>>> sor
[('b', 0), ('c', 1), ('a', 2)]
>>> for i in sor:
...     print i[0]
...
b  
c 
a
Maorg
  • 83
  • 8