Python Program to Count Word Frequency Using a Dictionary
hardDictionariesPython
Dictionaries map a key to a value — perfect for counting how often each word appears.
The question
Read a sentence of lowercase words separated by single spaces. Count how many times each word occurs using a dictionary, and print each word and its count in alphabetical order, one per line, like: word count
The code
program.py
words = input().split()
count = {}
for w in words:
count[w] = count.get(w, 0) + 1
for w in sorted(count):
print(w, count[w])Input
milk milk sun milk one sun code
Output
code 1 milk 3 one 1 sun 2
How it works
- 1split() turns the sentence into a list of words.
- 2count.get(w, 0) returns the current count, or 0 for a new word; add 1 and store it back.
- 3sorted(count) gives the words in alphabetical order for printing.
Common mistakes
- Writing count[w] += 1 for a new word — Python raises KeyError because the key does not exist yet.
- Printing the dictionary directly, which does not give one word per line.
Now solve a similar question yourself
A new Python question every time, checked instantly.
