Home › Errors › KeyError

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

How to debug it

  1. 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.
  2. In a nested chain like d['a']['b']['c'], the KeyError names the first missing link; split the chain to see which level failed.
  3. Decide the policy — required (keep [], fix the producer) or optional (switch to get() with a meaningful default).
  4. 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 नहीं करता।

पूरी Hindi explanation पढ़ें →

Related errors

Also related: AttributeError when you treat a dict value's type wrongly after lookup. Full list: Python errors guide.