Python KeyError: the dictionary key is missing
Exception: KeyErrorCategory: mapping lookupRaised at: runtime
What this error means
A dictionary was asked for a key it does not contain. The exception prints the requested key itself — KeyError: 'age' — which makes it one of Python's most self-documenting errors: you know exactly what was asked for; the question is only what the dict actually holds.
Keys match by equality and hash, exactly. 'Email', 'email' and 'email ' are three different keys. d[1] and d['1'] are different lookups — and since JSON object keys are always strings, data that crossed a JSON boundary is a frequent source of the int-vs-str mismatch.
A real example
user = {"name": "Asha", "email": "asha@example.com"}
print(user["age"])
Traceback (most recent call last):
File "app.py", line 2, in <module>
print(user["age"])
~~~~^^^^^^^
KeyError: 'age'
Whether this is a bug depends on the contract: if every user must have an age, the crash is correct and the bug is upstream where the dict was built. If age is optional, the lookup itself should have been user.get("age").
Choose the right lookup
d[key]— "this key must exist". Crashes loudly on absence; correct for required data.d.get(key, default)— "absence is normal". Returns the default, never raises, never inserts.d.setdefault(key, default)— get and store the default when missing; for building nested structures.d.pop(key, default)— remove-if-present; the crash-free version ofdel d[key].key in d— membership test alone, when you only need a yes/no.
How to debug it
- Put the key from the error message next to
print(list(d.keys()))and diff by eye — case, whitespace, and type account for most misses. - In a nested chain like
d['a']['b']['c'], the KeyError names the first missing link; split the chain to see which level failed. - Decide the policy — required (keep
[], fix the producer) or optional (switch toget()with a meaningful default). - Normalise keys once where the dict is created (
key.strip().lower()), not at every read site.
Fix it interactively
Real KeyError scenarios, each fixable in the browser:
Practice more Python bugs →🇮🇳 Hindi में समझें
Dictionary में वह key है ही नहीं जो आपने माँगी। Error message में वही key छपती है — उसे print(list(d.keys())) के output से मिलाओ: case, spacing या type का फर्क निकलेगा ('Naam' ≠ 'naam')। Key optional हो तो d.get(key, default) use करो — crash नहीं करता।
Related errors
- IndexError — the sequence twin — a missing position instead of a missing key.
- TypeError — chained .get() calls produce 'NoneType' is not subscriptable one level deeper.
Also related: AttributeError when you treat a dict value's type wrongly after lookup. Full list: Python errors guide.