python - 按 utf-8 的降序按值对 dict 进行排序
问题描述
我有一本这样的字典:{'ex1': 3, 'ex2': 4, 'ex3': 3}
我想按值对其进行排序。所以我这样做:results = sorted(results.items(), key=lambda x: x[1], reverse=True)
。我放reverse=True
是因为我希望它按降序排序。
所以代码是这样的:
results = {'ex1': 3, 'ex2': 4, 'ex3': 3}
results = sorted(results.items(), key=lambda x: x[1], reverse=True)
for item in results:
print (item[0])
输出是:
ex2
ex1
ex3
但我想要的输出应该是这样的:
ex2
ex3
ex1
因为在 utf-8 中,ex3 大于 ex1。
其实我想说的是,当两个键的值是偶数时,我想按降序打印它们。
我究竟做错了什么?提前感谢您的回答
解决方案
这应该有效 - 键函数可以返回一个元组:
results = {'ex1': 3, 'ex2': 4, 'ex3': 3}
results = sorted(results.items(), key=lambda x: (x[1],x[0]), reverse=True)
for item in results:
print (item[0])
给出输出:
ex2
ex3
ex1
推荐阅读
- python - 当我向 watson 的 api 发送文本消息时,Watson 对话节点不会调用该操作
- javascript - 如何使用 JavaScript 设置 SVG 元素的大小?
- c++ - 使用 PCL 进行点云下采样和正态估计
- postgresql - 如何在 postgres 中手动对所有行调用触发器
- javascript - 嵌套对象文字中“this”的词法上下文
- pandas - 如何在数据框中插入新列并使用 for 循环根据某些条件将值传递给它
- flutter - 颤动的应用程序可以在未运行时在接收推送通知时运行代码吗
- azure - 如何在没有任何授权令牌的情况下使用 Azure API for FHIR Server
- sql - Oracle 数据库中的 ASCII 字符问题
- angular - 如何使用现有行将另一个患者添加到表单中?