Python Program to Count the Frequency of Each Word in a String using Dictionary

This is a Python Program to count the frequency of words appearing in a string using a dictionary.

Problem Description

The program takes a string and counts the frequency of words appearing in that string using a dictionary.

Problem Solution

1. Enter a string and store it in a variable.
2. Declare a list variable and initialize it to an empty list.
3. Split the string into words and store it in the list.
4. Count the frequency of each word and store it in another list.
5. Using the zip() function, merge the lists containing the words and the word counts into a dictionary.
3. Print the final dictionary.
4. Exit.

Program/Source Code

Here is source code of the Python Program to count the frequency of words appearing in a string using a dictionary. The program output is also shown below.

test_string=raw_input("Enter string:")
wordfreq=[l.count(p) for p in l]
Program Explanation

1. User must enter a string and store it in a variable.
2. A list variable is declared and initialized to an empty list.
3. The string is split into words using a space as the reference and stored in the list.
4. The frequency of each word in the list is counted using list comprehension and the count() function.
5. The final dictionary is created using the zip() function and is printed.

Runtime Test Cases
Case 1:
Enter string:hello world program world test
{'test': 1, 'world': 2, 'program': 1, 'hello': 1}
Case 2:
Enter string:orange banana apple apple orange pineapple
{'orange': 2, 'pineapple': 1, 'banana': 1, 'apple': 2}

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

If you find any mistake above, kindly email to [email protected]

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.