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.
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'
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.
get()
, instead of directly accessing the key.try-except
block may be worthwhile if your code is new or untested.KeyError
in a try-except
construct. We print an error message in the except-block.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
The KeyError
is an avoidable exception in Python. It occurs when a dictionary is incorrectly used. We saw two ways to prevent this error.
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.