python - 按值对 python 中的字典进行排序,但保持相等值的键顺序

标签 python sorting python-2.7 dictionary

假设有一本字典

d = {"P1":77,"P2":89,"P3":77}

我想以下面的形式打印结果

P2:89

P1: 77

P3:77

即按字典值排序,对于相等的值,先到先得(即 P1 在 P3 之前)

我做了以下

import collections
od = collections.OrderedDict(sorted(d.items(), key=lambda x:x[1], reverse=True))

给了

OrderedDict([('P2', 89), ('P3', 77), ('P1', 77)])

如何在 P3 之前获得 P1?

最佳答案

这样做:

od = collections.OrderedDict(sorted(d.items(), key = lambda x:(-x[1],x[0])))

正如@Padraic 所说,“你不能从最高到最低和从最低到最高排序。”因此,您必须欺骗 sorted 函数,使其将最高数字视为最低数字。它按键的自然顺序进行子排序。

关于python - 按值对 python 中的字典进行排序,但保持相等值的键顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24972032/

相关文章:

python - 如何在 Google Colab 中进行文本到语音的转换?

python - 多对多或一对多 Django

python - 使用 virtualenv 修复 Mac 上的 Python 3 tkinter 问题

java - 双属性上的比较器排序无法满足其一般契约

python - django.db.utils.OperationalError : (1426,“精度太大1000

python - Pygame 文本变量不显示类型错误 : text must be a unicode or bytes

algorithm - 最大化对由值界定的排序数组的总和做出贡献的因素数

c# - MS Access 排序(比较字符串数据)

python - 让 Scapy 在 Windows 上工作时出错 : "' module' object has no attribute 'ex_name' "

OpenCV 2.4.8 : module compiled against API version 9