Finding the Frequency of every word from an Input using Dictionary in Python
Hey Coder, In this article we will learn to find the frequency of all words from the input using the Dictionary Data structure.
Counting words using Dictionary in Python
Dictionary stores the data in the form of key: value, where every key is unique. {} or dict() method can be used to create a dictionary.
We can store a value with a key and using the same key we can extract the value.
In this program, we are going to store different words as keys and the frequencies of each word as the value to the respective key.
The get member of the dictionary returns the value of the key in the dictionary. If there is no such key it returns a default value, without specifying a default value None is returned.
Syntax of get – dict_name.get( key [, default])
In this program, we are going to set the default value to Zero and also increase the value of the key by one when the word occurs one or more times in the Input.
Program: Frequency of every word from an Input using Dictionary in Python
Declare a Dictionary object count to store the set of pairs of word: frequency.
Prompt for the input from the user and store it into a variable input_line.
Split the input_line into a list of words using split() member and store them to the variable list_of_words.
Using a for loop, iterate over each word in list_of_words as a variable word for each iteration.
Using get member of the dictionary count, get the value of the key using count.get(word,0) and increase the value by 1 and update the new value of the key word to count[word].
Finally, display the words and their frequencies using a for loop, iterating through the keys in the count as key variable and printing key and count[key].
count = {} input_line = input("Enter a Line : ") list_of_words = input_line.split() for word in list_of_words: count[word] = count.get(word, 0) + 1 print('Word Frequency') for key in count.keys(): print(key, count[key])
Input :
Today we have learnt how to find the frequency of each and every word of input line from the user using a dictionary in Python
Output :
Word Frequency Today 1 we 1 have 1 learnt 1 how 1 to 1 find 1 the 2 frequency 1 of 2 each 1 and 1 every 1 word 1 input 1 line 1 from 1 user 1 using 1 a 1 dictionary 1 in 1 Python 1
Hi say, in my homework the professor asks me to display just the 10 first words with their respective frequency, it has to look something like this:
Word Count
=======================
a 631
a-piece 1
abide 1
able 1
about 94
above 3
absence 1
absurd 2
How can I do this?