|
| Home |
|---|
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.
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.
A KeyError occurs when a dictionary key that does not exist is accessed directly.
student = {
"name":"Alice",
"age":21
}
print(student["course"])
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.
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.
The most direct way to avoid a KeyError is to check whether the key exists in the dictionary before accessing it.
if key in dictionary:
print(dictionary[key])
student = {
"name":"Alice",
"age":21
}
if "course" in student:
print(student["course"])
else:
print("Key does not exist")
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.
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.
student = {
"name":"Alice",
"age":21
}
print(student.get("course"))
print(student.get("course", "Not Enrolled"))
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.
Exception handling with try/except lets a
program catch a KeyError and respond to it without crashing.
student = {
"name":"Alice",
"age":21
}
try:
print(student["course"])
except KeyError:
print("Key not found")
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.
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.
student = {
"name":"Alice",
"age":21
}
student.setdefault("course", "Not Enrolled")
print(student["course"])
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.
get() call would be clearer and shorterget() avoids the error but still returns None, which can cause a different error later if the code isn't expecting itA 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.
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.
No. get() never raises a KeyError. It returns
None, or a custom default value if one is provided,
whenever the key does not exist.
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.
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.
Home Tutorial Online Live Trainings Contact Us © 2026 All rights reserved by www.PythonTutor.net