Python Program to Count words in a String using Dictionary

Write a Python Program to Count Words in a String using Dictionary with a practical example.

Python Program to Count Words in a String using Dictionary Example 1

In this python program, we are using a split function to split the string. Next, we used for loop to count words in a string. Then we used the Python dict function to convert those words and values to the Dictionary.

# Python Program to Count words in a String using Dictionary

string = input("Please enter any String : ")
words = []

words = string.split()
frequency = [words.count(i) for i in words]

myDict = dict(zip(words, frequency))
print("Dictionary Items  :  ",  myDict)
Python Program to Count words in a String using Dictionary 1

Python Program to return String words using Dictionary Example 2

This Python code to count string words using Dictionary is another approach to count string words. Here, we used for loop to iterate words.

# Python Program to Count words in a String using Dictionary

string = input("Please enter any String : ")
words = []

words = string.split() # or string.lower().split()
myDict = {}
for key in words:
    myDict[key] = words.count(key)

print("Dictionary Items  :  ",  myDict)

Counting words in a string using a dictionary output

Please enter any String : python tutorial at tutorial gateway web
Dictionary Items  :   {'python': 1, 'tutorial': 2, 'at': 1, 'gateway': 1, 'web': 1}