Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 415
delsin Avatar asked Dec 19 '22 17:12

delsin


2 Answers

sorted_keys = sorted(my_dict, key=my_dict.get)
like image 155
georg Avatar answered Dec 21 '22 10:12

georg


>>> d={'a': 2, 'b': 0, 'c': 1}
>>> [i[0] for i in sorted(d.items(), key=lambda x:x[1])]
['b', 'c', 'a']
like image 27
riteshtch Avatar answered Dec 21 '22 10:12

riteshtch