我有一个这样的字典:{'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。
实际上我想说的是,当两个键具有偶数值时,我想按降序打印它们。
我究竟做错了什么?
在此先感谢您的回答
答案 0 :(得分:2)
这应该工作-关键函数可以返回一个元组:
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