-2

I created a dictionary that counts the number of occurrences of each word in a separate text file. So far it looks like this.

import sys

def main():
    d = dict({})
    
    with open(sys.argv[1], encoding="utf-8") as f:
        for line in f: 
            line = line.strip() 
            line = line.lower() 
            words = line.split(" ")
            for word in words: 
                if word in d: 
                    d[word] = d[word] + 1
                else: 
                    d[word] = 1
    
    for key in list(d.keys()):
        print(key, ":", d[key])
    
if __name__ == "__main__":
    main()

In the command line, I input a text file for it to count the frequencies of each word (executing "python3 frequencycount.py example.txt"). This code effectively executes a list of all words in the text file and it counts how many times they occur. What I'm trying to do now is print the words in descending order by frequency of occurrence.

For example, my text file is a list of vegetables (pepper 5 times, carrot 9 times, peas 8 times, and broccoli 1 time). The list looks like this:

Pepper : 5
Carrot : 9
Peas : 8
Broccoli : 1

However, I would want it to print like this:

Carrot : 9
Peas : 8
Pepper : 5
Broccoli : 1

How can I make it print in descending order like this? Thanks.

coda
  • 125
  • 1
  • 3
  • 11

2 Answers2

2

You can iterate over a sorted list of keys, where the sort key is the values of the dict itself, with reverse=True making it descending order.

d = {
'Pepper' : 5,
'Carrot' : 9,
'Peas' : 8,
'Broccoli' : 1,
}


for key in sorted(d, key=d.get, reverse=True):
    print(key, ":", d[key])

Output

Carrot: 9
Peas : 8
Pepper : 5
Broccoli : 1
Chris
  • 15,819
  • 3
  • 24
  • 37
1
d = sorted(d.items(), key=lambda x: x[1], reverse=True)

for i in d:
    print(i[0], i[1])
zerecees
  • 697
  • 4
  • 13