Lingua-e
Python

What is a KeyError?

← Errors

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.

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'

How to fix it

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.

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"))

Related errors

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