When it is required to count the frequency of words that appear in a string with the help of dictionary, the ‘split’ method is used to split the values, and a list comprehension is used.
The list comprehension is a shorthand to iterate through the list and perform operations on it.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
Example
Below is a demonstration for the same −
my_string = input("Enter the string :") my_list=[] my_list=my_string.split() word_freq=[my_list.count(p) for p in my_list] print("The frequency of words is ...") print(dict(zip(my_list,word_freq)))
Output
Enter the string :Hi jane how are you jane The frequency of words is ... {'Hi': 1, 'jane': 2, 'how': 1, 'are': 1, 'you': 1}
Explanation
- A string is entered by the user, and is assigned to a variable.
- An empty list is created.
- The string is split, and put in the list.
- A list comprehension is used to iterate over the list, and the ‘count’ method is used to count the values.
- This is assigned to a variable.
- The list and word frequency are zipped, and converted to a dictionary.
- It is then displayed on the console.