Python Code to Count Frequency of Word-[ smart solution ]

Today we are going to learn how to count the frequency of the word in a list using the dictionary and simple for loop in python. The problem is – Suppose you have a list of words and using python you are supposed to count the frequency of each word.

count frequency of word

This program is a little bit different from the popular available solutions on the internet. Where a word is stored in the python dictionary as a key and its frequency as its value.

In our case, you are required to store the frequency as a dictionary key and the words as its value. For example

sample list is  ['the','is','in','the','ram','suresh','is','atul']
The output must be {2:['the','is'],1:['is','ram','suresh','atul']

Since a dictionary is known as an immutable data type ie we can not make changes inside the dictionary once defined. Thus to solve this problem we have followed two methods.

1. Methods using list and dictionary to find out frequency of word in a list

L = ['the', 'in', 'out', 'the', 'in', 'ram', 'umesh', 'the']
d = {}

l = len(L)
for i in range(0, l):
    key = L.count(L[i])
    if key not in d:
        value = []
        for j in range(i, l):
            if(L.count(L[j]) == key and L[j] not in value):
        d[key] = value

The second method is little bit lengthy. here is the second method

for i in L:
    c = L.count(i)
    if c not in d:
        d[c] = [i]
    elif i not in d[c]:

The output of the above frequency program

{3: ['the'], 2: ['in'], 1: ['out', 'ram', 'umesh']}

In this last solution, we are traversing the whole list one element at a time and checking the frequency of that element. If the frequency match with other words of the list we append the elements in the dictionary otherwise just adding the element in the dictionary.

hope you would like these solutions. If you have any other solution to this simple problem, let us know.

Print Friendly, PDF & Email

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to See your article appearing on the main page and help other students/teachers.