Python Tutoring Online
 Home

Python KeyError in Dictionary

A KeyError is one of the most common errors Python programmers encounter when working with dictionaries. It occurs when code tries to access a dictionary key using square brackets (dictionary[key]) and that key does not exist in the dictionary.

In this tutorial you will learn exactly why KeyError happens, how to read the error message and traceback, and four different ways to prevent it — using the in operator, the get() method, try/except, and setdefault() — along with when to use each one.

Need Help Learning Python?

Many beginners encounter errors like KeyError when working with Python dictionaries and data structures.

Working with an experienced Python tutor can help you understand debugging techniques and solve coding problems faster.

Get Python Tutoring Help

What Causes a KeyError?

Dictionaries store data as key-value pairs, and square-bracket access (dictionary[key]) assumes the key you're asking for already exists. Python has no way to guess what value you meant if the key is missing, so instead of silently returning nothing, it immediately raises a KeyError and stops the program unless the error is handled.

Example of KeyError

A KeyError occurs when a dictionary key that does not exist is accessed directly.

Python
student = {
"name":"Alice",
"age":21
}
print(student["course"])

Output


KeyError: 'course'

The dictionary contains the keys name and age, but the program tries to access the key course. Because this key is not present in the dictionary, Python raises a KeyError.

Reading a KeyError Traceback

In a real program, a KeyError produces a full traceback, not just the short message shown above.


Traceback (most recent call last):
  File "main.py", line 5, in <module>
    print(student["course"])
KeyError: 'course'

The last line, KeyError: 'course', tells you exactly which key was missing. The line above it points to the exact line of code where the missing key was accessed — always check that line first, since it's usually a typo, an unexpected user input, or a key that was never added to the dictionary in the first place.

Fix 1: Check if the Key Exists Using the in Operator

The most direct way to avoid a KeyError is to check whether the key exists in the dictionary before accessing it.

Syntax

Python
if key in dictionary:
    print(dictionary[key])

Example

Python
student = {
"name":"Alice",
"age":21
}

if "course" in student:
    print(student["course"])
else:
    print("Key does not exist")

Output


Key does not exist

The program checks whether the key exists first. Since the key is not present, it safely prints a message instead of raising an error. This approach is best when you need to run different code depending on whether the key exists.

Fix 2: Using the get() Method

The get() method is the most common way to access dictionary values safely, since it never raises a KeyError.

If the key exists, get() returns its value. If the key does not exist, it returns None by default — or a custom fallback value if you provide one as a second argument.

Python
student = {
"name":"Alice",
"age":21
}

print(student.get("course"))
print(student.get("course", "Not Enrolled"))

Output


None
Not Enrolled

Because the key course does not exist, the first call returns None, and the second call returns the custom default "Not Enrolled" instead. This is usually the cleanest fix when you just need a value and don't need separate logic for the missing-key case.

Fix 3: Using try/except

Exception handling with try/except lets a program catch a KeyError and respond to it without crashing.

Python
student = {
"name":"Alice",
"age":21
}

try:
    print(student["course"])
except KeyError:
    print("Key not found")

Output


Key not found

The program attempts to access the missing key, and instead of crashing, the except KeyError: block catches the error and handles it gracefully. This approach is most useful when accessing the key is expected to normally succeed, and a missing key represents a genuinely exceptional situation worth logging or reporting separately.

Fix 4: Using setdefault() to Prevent Future KeyErrors

If you plan to access the same key multiple times, setdefault() can insert a default value once, so later square-bracket access never raises a KeyError for that key again.

Python
student = {
"name":"Alice",
"age":21
}

student.setdefault("course", "Not Enrolled")
print(student["course"])

Output


Not Enrolled

Unlike get(), which only returns a default without changing the dictionary, setdefault() permanently adds the key with the default value, so any future access to student["course"] in the program will succeed safely.

Which Fix Should You Use?

Common Causes of KeyError

Common Beginner Mistakes

Frequently Asked Questions

What is the difference between KeyError and IndexError?

A KeyError happens when a dictionary key does not exist. An IndexError happens when a list or tuple index is out of range. They are separate exception types for separate data structures.

What is the best way to avoid a KeyError?

For most cases, dictionary.get(key, default) is the simplest and most readable fix, since it returns a safe value in one line without needing a separate if check.

Does get() raise a KeyError if the key is missing?

No. get() never raises a KeyError. It returns None, or a custom default value if one is provided, whenever the key does not exist.

Can a KeyError happen when deleting a key?

Yes. Using del dictionary[key] or dictionary.pop(key) on a key that doesn't exist also raises a KeyError, unless pop() is given a default value as its second argument.

Related Python Dictionary Tutorials




Stuck Learning Python?

Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.

Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.

    Get Python Tutoring

PythonTutor.net

Home    Tutorial     Online Live Trainings    Contact Us           © 2026 All rights reserved by www.PythonTutor.net