首页 > 解决方案 > 按值排序后如何按字母顺序对字典的键进行排序?

问题描述

from collections import Counter

with open("text.txt", encoding='utf-8') as file:
    data = file.read()
    words = data.split()

count_dict = dict(Counter(words))

for key, value in sorted(count_dict.items(), key=lambda x: x[1], reverse=True):
    print(f'{key}: {value} time(s)')

对于文件:

abc  
aab  
abc  
abb  
abb  

这返回:

abc: 2 time(s)
abb: 2 time(s)
aab: 1 time(s)

虽然它应该返回:

abb: 2 time(s)  
abc: 2 time(s)  
aab: 1 time(s)

在按次数(值?

标签: pythonpython-3.xsorting

解决方案


需要稍作改动:

等效的方法是使用计数的负值,而不是指定sorted函数reverse-True 。现在我们正在使用计数的负数进行升序排序,我们可以使用包含作为“辅助列”的键的组合键进行排序:

for key, value in sorted(count_dict.items(), key=lambda x: (-x[1], x[0])):
    print(f'{key}: {value} time(s)')

把它们放在一起:

from collections import Counter

with open("text.txt", encoding='utf-8') as file:
    data = file.read()
    words = data.split()

count_dict = dict(Counter(words))

for key, value in sorted(count_dict.items(), key=lambda x: (-x[1], x[0])):
    print(f'{key}: {value} time(s)')

印刷

abb: 2 time(s)
abc: 2 time(s)
aab: 1 time(s)

推荐阅读