python - 按 utf-8 的降序对字典进行排序

标签 python python-3.x string sorting dictionary

我有一个像这样的字典:{'ex1': 3, 'ex2': 4, 'ex3': 3},我想按值对其进行排序。所以我这样做:结果=排序(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。
其实我想说的是,当两个键的值为偶数时,我想按降序打印它们。
我究竟做错了什么? 预先感谢您的回答

最佳答案

这应该可行 - key 函数可以返回一个元组:

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 - 按 utf-8 的降序对字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58954153/

相关文章:

python - Seaborn Violinplot 更改色调顺序

Python - 如何从一个数组值乘以另一个数组的所有值创建新的乘积和数组

python-3.x - 使用 python3.7 在 ubuntu 16.04 上安装 python functools32 时出错

python - 使用记录器对象而不是使用日志记录有什么好处?

java - 字符串[]转字符串

python - 从文件中读取模式并使用python写入另一个文件

c++ - 为静态库编译 SWIG Python 包装器?

python - 尝试在 Windows 7 中的 Anaconda(python) 上安装 pymc 并出现奇怪的错误?

ruby - 字符串包含

C# 在数组中保存对字符串变量的引用