对字典进行降序排序,当数字相同时按升序排序

Sort a dictionary in decreasing order and in increasing order when there is a same number

我需要对 python 中的字典进行降序排序,但是当字典中的数字是数字的两倍时,我需要对这些数字进行升序排序:

示例:

词典:

t = {0: 8, 1: 4, 2: 4, 3: 0, 4: 3, 5: 6, 6: 8, 7: 8, 8: 1, 9: 3}

我的代码:

dict(sorted(t.items(), reverse=True, key=lambda item: item[1]))

输出:

{0: 8, 6: 8, 7: 8, 5: 6, 1: 4, 2: 4, 4: 3, 9: 3, 8: 1, 3: 0}
                         ^^^^^^^^^^

需要输出:

{0: 8, 6: 8, 7: 8, 5: 6, 2: 4, 1: 4, 4: 3, 9: 3, 8: 1, 3: 0}
                         ^^^^^^^^^^ 

我如何使用 lambda 函数做到这一点?

提前感谢您的任何回复

在相同值的情况下按降序获取键,只需在lambda函数中添加键即可:

key=lambda item: (item[1], item[0])

因为这确实颠倒了 item 的顺序,您也可以这样做:

key=lambda item: item[::-1]