Python Dictionary Practice: Count Repeated Words
Frequency dictionaries are useful when summarising events, tags or words. This small example counts whitespace-separated tokens. It deliberately keeps the rules simple so you can see how each loop iteration changes the dictionary.
Before you start: Python strings, for loops and dictionary keys.
Your task
Split the sentence on whitespace and count each word with a dictionary. Print the counts for code and learn.
Starter code
sentence = "code learn code build learn code"
counts = {}
# Count each word in sentence.split().
print(counts.get("code", 0))
print(counts.get("learn", 0))
Expected result
3
2Loads the starter in the workspace. Save or export existing work first. Return here for hints and the explanation.
Need a hint?
For each word, read its previous count with counts.get(word, 0), add one, and assign the new count back to that key.
Show the complete solution and walkthrough
sentence = "code learn code build learn code"
counts = {}
for word in sentence.split():
counts[word] = counts.get(word, 0) + 1
print(counts.get("code", 0))
print(counts.get("learn", 0))
- sentence.split() produces the words in their original order, splitting on whitespace. The loop processes repeated words separately.
- A word that has not appeared yet has no dictionary entry. dict.get(word, 0) provides the starting value without raising KeyError.
- Write the incremented count back into counts. After the loop, the existing print calls output the count for code and then learn: 3 and 2.
A common mistake
Assigning counts[word] = 1 every time resets repeated words. Reading counts[word] before its first assignment can raise KeyError.
Try an edge case
An empty sentence produces no words; the existing get calls then print 0 and 0. Code and code are different keys, and code, includes punctuation.
Take it one step further
Try sentence.lower().split() to ignore case. Decide separately how punctuation should be handled; lower() does not remove it.