如何基于具有元组的值对字典进行排序

时间:2018-01-05 07:06:51

标签: python-3.x

这里我有像

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

我必须根据元组中第一个值的降序对其进行排序。 我这样做:

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

但我得到了这个:

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

输出应如下所示:

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

2 个答案:

答案 0 :(得分:1)

您可以尝试:

>>> [(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))]

注意:此答案的最后两个元素与OP提供的示例答案交换。

答案 1 :(得分:1)

这样简单的东西也可以起作用:

>>> 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))]