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)')
for the file:
abc
aab
abc
abb
abb
this returns:
abc: 2 time(s)
abb: 2 time(s)
aab: 1 time(s)
while it should return:
abb: 2 time(s)
abc: 2 time(s)
aab: 1 time(s)
How can I put the words (keys) alphabetically after they have been sorted by number of times(value?