有没有一种方法可以将字典按照数字顺序排序,包括负数?

huangapple go评论67阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月6日 06:17:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76410323.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定