Help with sorting a list by dictionary value | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 13

Help with sorting a list by dictionary value

I have a dictionary that's like this: {0: "20" , 1: "10" , 2: "30"} I want to make a list out of it that arranges the dictionary names by how high their value is. I want the list to look like this: [2, 0, 1] I've tried sorted(dict, key=dict.get, reverse=True) and while it SEEMS to work at first glance, it doesn't sort it correctly when I have a bunch of keys. Thank you if you can help.

18th Feb 2017, 5:37 AM
Ahri Fox
Ahri Fox - avatar
2 Answers
+ 4
a = {0:"20",1:"10",2:"30"} b = sorted(((k,int(v)) for k,v in a.items()),key=lambda x:x[1])[::-1] print([x[0] for x in b])
18th Feb 2017, 7:23 AM
richard
+ 10
Thank you so much StarLord! Works perfectly in my code! edit: I might have entered it wrong, I am tired, but StarLord's seemed to make repeat numbers. richard's code was the next best thing so thank you richard!
18th Feb 2017, 6:36 AM
Ahri Fox
Ahri Fox - avatar