英文:
Is there a way to sort a dictionary into number order with negative numbers?
问题
你想要将字典按照负数的顺序排序,你可以使用以下方式:
sorted_dict = sorted(my_dict, key=lambda x: my_dict[x])
这将根据字典中的值进行排序,所以输出会是 ['b', 'c', 'a', 'd']
,符合你的要求。
英文:
I am trying to sort a dictionary into an order with negative numbers. This seems like an easy task but for some reason I can't get it. I've seen a few similar solutions but they're either not exactly what I'm looking for or I can't get them to work for me. I know it is something to do with the key but I don't know what. I would preferably want the final output to be a list if possible.
number1 = 1
number2 = -5
number3 = -2
number4 = 3
my_dict = {"a" : number1,
"b" : number2,
"c" : number3,
"d" : number4
}
sorted_dict = sorted(my_dict, key= ???)
I would want something like:
#output
['b', 'c', 'a', 'd']
#so -5 -2 1 3
答案1
得分: 2
你想要按值而不是键进行排序。使用以下代码:
sorted_dict = sorted(my_dict, key=my_dict.get)
print(sorted_dict)
将得到:
['b', 'c', 'a', 'd']
英文:
You want to sort on the values not the keys. Use:
sorted_dict = sorted(my_dict, key= my_dict.get)
print(sorted_dict)
to give:
['b', 'c', 'a', 'd']
答案2
得分: 0
以下是要翻译的内容:
"key"参数在sorted中需要是一个接受第一个位置参数的每个元素的函数。它根据该函数的输出对第一个参数进行排序。
英文:
Something like this ought to do it
sorted(my_dict.keys(), key=lambda x: my_dict[x])
The key
argument in sorted needs to be a function that accepts each element of the first positional argument. It sorts the first argument based on the output of that function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论