Write a function that counts how many times each word appears in a string.
word_frequency(text)
Return a dict mapping each word to its count. Words are separated by single spaces.
word_frequency("a b a c b a") // → {"a": 3, "b": 2, "c": 1}
word_frequency("x x x") // → {"x": 3}
This is the exact counting pattern from the dictionaries lesson, applied directly:
def word_frequency(text):
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
return counts
text.split() gives you the individual words. For each one, counts.get(word, 0) looks up its current count — or 0, if this is the first time that word has shown up (since it isn't in counts yet, and .get() returns the default instead of raising KeyError). Adding 1 to that and assigning it back to counts[word] handles both cases uniformly: a brand-new word gets 0 + 1 = 1, and a word seen before gets incremented from whatever it already was.
This is exactly what collections.Counter does under the hood, from the previous section — here you're building the same logic by hand, which is worth doing once so the Counter shortcut isn't a black box.
def word_frequency(text):
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
return counts
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.