2
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?

StefWS
  • 35
  • 5
  • 1
    What is your intended output? , the output you are showing is alphabetically sorted already – Vaebhav Jul 21 '21 at 11:16
  • It was badly formulated and has been corrected. – StefWS Jul 21 '21 at 11:47
  • Does this answer your question? [Sort a list of tuples depending on two elements](https://stackoverflow.com/questions/9376384/sort-a-list-of-tuples-depending-on-two-elements) – mkrieger1 Jul 21 '21 at 12:05
  • I've changed using `print` in the list comprehension to a normal `for` loop because it's a bad practice and doesn't matter for the question. – mkrieger1 Jul 21 '21 at 12:09
  • Lots of thanks @Booboo & @Vaebhav!! – StefWS Jul 22 '21 at 16:19

3 Answers3

1

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)
Booboo
  • 38,656
  • 3
  • 37
  • 60
1

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


Vaebhav
  • 4,672
  • 1
  • 13
  • 33
0

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.

Jacek Błocki
  • 452
  • 3
  • 9