StefWS
StefWS

Reputation: 35

How to sort the keys of a dictionary alphabetically after sorting them by value?

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?

Upvotes: 2

Views: 134

Answers (3)

Jacek Błocki
Jacek Błocki

Reputation: 563

You want values (numbers) sorted in descending and keys (words) in ascending order. You can try this:

sorted(count_dict.items(), key=lambda x: (-x[1], x[0]))

Negative values in sort key do the job.

Upvotes: 0

Vaebhav
Vaebhav

Reputation: 5032

You can use the negative sign with the values and give precedence to keys afterwards like this -

>>> from collections import Counter
>>> l = ["abc","aab","abc","abb","abb"]
>>> l
['abc', 'aab', 'abc', 'abb', 'abb']
>>> count_dict = Counter(l)

#### Negative Value is assigned to count_dict values
>>> sorted(count_dict.items(), key=lambda x: (-x[1],x[0]))
[('abb', 2), ('abc', 2), ('aab', 1)]

>>> 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)
>>> 


Upvotes: 1

Booboo
Booboo

Reputation: 44108

A slight change is needed:

Instead of specifying for the sorted function reverse-True, an equivalent approach is to use the negative value of of the count. Now that we are sorting ascending with the negative of the count, we can use a combined key that includes the key as a "secondary column" to sort on:

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

Putting it all together:

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)')

Prints

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

Upvotes: 1

Related Questions