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}

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.