python - 如何先按值排序字典,然后按键排序

标签 python python-3.x sorting dictionary

我有一本字典

d={'g':1,'w':1,'h':3}

首先,我想按键对值进行排序,因此最终输出应如下所示

d={'h':3,'g':1,'w':1}

最佳答案

从 Python 3.6 开始,字典是有序的,但为了确保需要使用 collections 模块中的 OrderedDict:

from collections import OrderedDict

d={'g':1,'w':1,'h':3}

o = OrderedDict(sorted(((k, v) for k, v in d.items()), key=lambda v: (-v[1], v[0])))
print(o)

输出:

OrderedDict([('h', 3), ('g', 1), ('w', 1)])

关于python - 如何先按值排序字典,然后按键排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51446082/

相关文章:

python - 枚举所有可能的数据类实例(仅包含枚举和 bool 字段)

python - 解包列表理解中元素的 "the rest"- python3to2

python - Django : Parsing Json data to template

python - 使用 python 3.x 时,如何从 "for"命令获取输出并将它们添加到列表或字符串中?

python - pandas.DataFrame.replace 更改列的 dtype

python - 删除一行中特定单词的重复

c++ - 编译时拓扑排序超出 C++ 中的递归深度

c# - 从列表中的列表中按项目排序

algorithm - 合并排序中的递归、快速排序和树的遍历

python - Sanic 和 Motor 使用不同的事件循环