AnyCompiler
← Blog

September 16, 2026

KeyError in Python: How to Avoid It With .get() and defaultdict

Looking up a dictionary key that doesn't exist raises a KeyError and stops your program — here's the exact error, and two idiomatic ways around it.

prices = {"apple": 1.5, "banana": 0.5}
print(prices["mango"])
Output
Traceback (most recent call last):
  File "script.py", line 2, in <module>
    print(prices["mango"])
KeyError: 'mango'

Fix #1: .get() with a default value

prices = {"apple": 1.5, "banana": 0.5}
print(prices.get("mango", 0))
print(prices.get("apple", 0))
Output
0
1.5

prices.get("mango", 0) returns 0 (the default you gave it) instead of raising an error, and still returns the real value for a key that does exist — no behavior change for the normal case, just a graceful fallback for the missing one.

Fix #2: defaultdict for counting and grouping

from collections import defaultdict

counts = defaultdict(int)
for word in ["a", "b", "a", "c", "b", "a"]:
    counts[word] += 1

print(dict(counts))
Output
{'a': 3, 'b': 2, 'c': 1}

defaultdict(int) automatically creates a missing key with a starting value of 0 the first time it's accessed, instead of raising a KeyError — which is exactly what a counting loop like counts[word] += 1 needs, without a separate check for whether the key already exists.

For more on creating, updating, and reading dictionaries, see the Dictionaries lesson in our free Python course.