+ 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.
5 ответов
+ 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])
+ 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!