BugLab016 / 020up to 100
dictsKeyErrormethodsmedium

Missing Key

The function word_frequency(words) should take a list of words and return a dictionary mapping each word to how many times it appears.

It crashes on the very first word every single time. The error happens on a line that looks perfectly logical.

Why does Python refuse to increment something that doesn't exist yet?

# your fix
+ must call get()
hint 2after hint 1
hint 3after hint 2
solution

Read the code. Before running anything: what does the last line below give?

def word_frequency(words):
"""
Returns a dictionary mapping each word to the number of times
it appears in the list.
Example: word_frequency(["a", "b", "a"]) -> {"a": 2, "b": 1}
"""
freq = {}
for word in words:
freq[word] += 1
return freq
>>> word_frequency(['a'])