我试图按值排序字典,我看到这篇文章: Sort a Python dictionary by value
我只需要获得列表中值较大的键,而不是元组,所以我写了这个(看起来有点笨拙)。 但是如果2个键具有相同的值,我需要以字母方式对它们进行排序。
这是我试图做的事情:
import operator
final_sort=[]
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
for item in sorted_x[::-1]:
final_sort.append(item[0])
但这仅适用于数值条件。
例如:
inp : x = {'a': 2, 'b': 4, 'c': 6, 'd': 6, 'e': 0}
out : ['c', 'd', 'b', 'a', 'e']
答案 0 :(得分:2)
迭代字典会产生密钥;您可以将字典本身传递给sorted
。
>>> x = {'a': 2, 'b': 4, 'c': 6, 'd': 6, 'e': 0}
>>> sorted(x, key=lambda key: (-x[key], key))
['c', 'd', 'b', 'a', 'e']
答案 1 :(得分:0)
这是我的选择,分2步
>>> x = {'a': 2, 'b': 4, 'c': 6, 'd': 6, 'e': 0}
>>> sorted(x.items(), key=lambda i: i[1], reverse=True)
[('c', 6), ('d', 6), ('b', 4), ('a', 2), ('e', 0)]
>>> [x[0] for x in sorted(x.items(), key=lambda i: i[1], reverse=True)]
['c', 'd', 'b', 'a', 'e']