Back to questionsWhy does this word counter raise
MiddleDebuggingRare
Why does this word counter raise KeyError?
This counts word frequencies, but crashes on the first word.
def count_words(text):
counts = {}
for w in text.split():
counts[w] += 1
return countsFind and fix the bug.
counts[w] += 1 reads counts[w] before the key exists → KeyError on the first sight of each word. Fix: counts[w] = counts.get(w, 0) + 1, or use collections.defaultdict(int), or simply collections.Counter(text.split()).
- Assuming
dict[k] += 1auto-initializes a missing key to 0 - Blaming
splitor the return rather than the missing-key read - Not reaching for
defaultdictorCounter
- How does
collections.defaultdict(int)change what happens on a missing key? - When is
dict.setdefaultpreferable togetfor this pattern?