简体   繁体   中英

How to sort keys of dict by values?

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?

 sorted_keys = sorted(my_dict, key=my_dict.get)

try this:

import operator
lst1 = sorted(lst.items(), key=operator.itemgetter(1))
>>> d={'a': 2, 'b': 0, 'c': 1}
>>> [i[0] for i in sorted(d.items(), key=lambda x:x[1])]
['b', 'c', 'a']

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])
>>> 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM