Lingua-e
← Errors
Python

KeyError: What It Means and How to Fix It

Error reference

KeyError

Language

Python

Severity

Medium

When it happens

A KeyError is raised in Python when you try to access a dictionary key that does not exist.

Potential fixes

Use the .get() method with a default value, or check with the in operator before accessing. If you expect the key to always be there, log or validate the data that builds the dictionary.

Deep dive

A KeyError is raised in Python when you try to access a dictionary key that does not exist. Python cannot find the key you requested, so it raises this error instead of returning a value.

Why it happens

  • Accessing a key that was never added to the dictionary.
  • Typo in the key name (e.g. 'Email' vs 'email').
  • The key was deleted earlier in the program with del or .pop().
  • Assuming a key exists without checking, for example when reading API responses or user input.

Potential fixes

Use the .get() method with a default value, or check with the in operator before accessing. If you expect the key to always be there, log or validate the data that builds the dictionary.

Examples

Python

Code that triggers the error

user = {"name": "Alice", "age": 30}
print(user["email"])

Error output

Traceback (most recent call last):
  File "app.py", line 2, in <module>
    print(user["email"])
KeyError: 'email'

Fixed code

user = {"name": "Alice", "age": 30}
# Option 1: check first
if "email" in user:
    print(user["email"])

# Option 2: use .get() with a default
print(user.get("email", "not provided"))

Practice in English

How would you explain a KeyError to a fellow dev? Choose the right phrase:

"I hit an error...

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free