简体   繁体   English

如何使用元组根据值对字典进行排序

[英]How to sort a dictionary based on values with tuple

Here I have dictionary like在这里我有字典

d_ = {"k3":(2,3), "k1":(4,5), "k5":(8,9), "k2":(6,8), "k4":(2,7)}

I have to sort this based on descending order of first value in the tuples.我必须根据元组中第一个值的降序对其进行排序。 I am doing this:我正在这样做:

 sorted(d_.items(), key=d_.get(1) , reverse=True)

But I am getting this:但我得到了这个:

[('k5', (8, 9)), ('k4', (2, 7)), ('k3', (2, 3)), ('k2', (6, 8)), ('k1', (4, 5))]

The Output should look like this:输出应如下所示:

[("k5",(8,9)),("k2",(6,8)),("k1",(4,5)),("k3",(2,3)),("k4",(2,7))] 

You can try:你可以试试:

>>> [(k, d_.get(k)) for k in sorted(d_, key=d_.get, reverse=True)]
[('k5', (8, 9)), ('k2', (6, 8)), ('k1', (4, 5)), ('k4', (2, 7)), ('k3', (2, 3))]

NOTE : The last two elements for this answer are swapped from the example answer the OP gave.注意:此答案的最后两个元素与 OP 给出的示例答案交换。

Something as simple as this could also work:像这样简单的事情也可以工作:

>>> d_ = {"k3":(2,3), "k1":(4,5), "k5":(8,9), "k2":(6,8), "k4":(2,7)}
>>> sorted(d_.items(), key = lambda x : -x[1][0])
[('k5', (8, 9)), ('k2', (6, 8)), ('k1', (4, 5)), ('k3', (2, 3)), ('k4', (2, 7))]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM