KeyError in Python
Updated
A Python KeyError prints only the missing key, such as KeyError: 'user'. What it means, where missing keys come from, and four ways to fix it.
What you see
config = {"host": "localhost", "port": 8080}
print(config["user"])Traceback (most recent call last):
File "/home/me/project/main.py", line 2, in <module>
print(config["user"])
~~~~~~^^^^^^^^
KeyError: 'user'What it means
You looked up a key the dict does not have. A KeyError message is nothing but that key, 'user' here, so the quoted word on the last line is the answer to "what was missing".
Why it happens
- A spelling or case difference.
"User"and"user"are different keys; so are"user"and"user "with a trailing space. - Data that lacks a field, such as JSON from an API that leaves out empty fields.
- An environment variable that is not set.
os.environ["API_KEY"]raisesKeyError: 'API_KEY'. - A pandas column name that does not match, often because of spaces in a CSV header.
How to fix it
Use get() when a missing key is normal, with a default if you want one:
user = config.get("user") # None when missing
user = config.get("user", "admin") # "admin" when missing
Check first when the missing case needs its own handling:
if "user" in config:
print(config["user"])
For counting or grouping, collections.defaultdict creates a key the first time you use it:
from collections import defaultdict
counts = defaultdict(int)
counts["ada"] += 1
For environment variables, os.environ.get("API_KEY") returns None instead of raising.
How each Python version words it
| Python | Prints |
|---|---|
| 3.9–3.15 | KeyError: 'user' |
Run on CPython 3.9.6, 3.10.22, 3.11.17, 3.12.15, 3.13.17, 3.14.9 and 3.15.1, on October 25, 2026.
The message is the same in every version here: the key, as repr() shows it.
Questions
Why is the message just a word?
KeyError carries the missing key as its only argument and prints it with repr(). Inside an except KeyError as e:, the key is e.args[0].
What does KeyError: 0 on a pandas DataFrame mean?
df[0] asks for a column named 0. To get the first row, use df.iloc[0].
Sources
- Built-in exceptions: KeyError, Python documentation
- Mapping types:
dict.get(), Python documentation - collections.defaultdict, Python documentation
Read on October 25, 2026.