首页 > 解决方案 > 按 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。
其实我想说的是,当两个键的值是偶数时,我想按降序打印它们。
我究竟做错了什么?提前感谢您的回答

标签: pythonpython-3.xstringsortingdictionary

解决方案


这应该有效 - 键函数可以返回一个元组:

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

推荐阅读