KeyError. In Python, a dictionary can cause a KeyError to occur. This happens due to incorrect use of the dictionary—like when we access a nonexistent key.
It is possible to prevent the KeyError in most cases by using the get() method on the dictionary. A default value returned, when the key does not exist, can also help.
Error example. This program causes a KeyError to be thrown. The dictionary contains 2 entries—these have the keys "cat" and "book." We try to access a key "python" but it does not exist.
# Get started.
values = {"cat" : 1, "book" : 2}
# There is no python in the dictionary.
print(values["python"])Traceback (most recent call last):
File "C:\programs\program.py", line 8, in <module>
print(values["python"])
KeyError: 'python'
Fixed example. A KeyError can be avoided. Usually, calling get() on the dictionary is the best solution, as this is a standard approach to using dictionaries in Python.
Tip We fix the problem by using a safe method, such as get(), instead of directly accessing the key.
Tip 2 If any direct accesses occur in your program, using a try-except block may be worthwhile if your code is new or untested.
Here We trap the KeyError in a try-except construct. We print an error message in the except-block.
Finally After handling exceptions, we access key "d" with the get() method. This is safe—no exception is raised.
# Create dictionary with three entries.
values = {"a" : 1, "b" : 2, "c" : 3}
# Using the value directly can cause an error.
try:
print(values["d"])
except KeyError:
print("KeyError encountered")
# We use get to safely get a value.
print(values.get("d"))KeyError encountered
None
Summary. The KeyError is an avoidable exception in Python. It occurs when a dictionary is incorrectly used. We saw two ways to prevent this error.
Some fixes. We used a try-except statement. And we replaced the value access with a get() method call. In most programs, calling get() is the best option.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.