KeyError FixLearn how to fix a KeyError, which is encountered when using a dictionary.
This page was last reviewed on Apr 27, 2022.
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.
Shows an error
Fixing the error. We can 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.Shows an error
# 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.
Detail We fix the problem by using a safe method, such as get(), instead of directly accessing the key.
Detail If any direct accesses occur in your program, using a try-except block may be worthwhile if your code is new or untested.
Next 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
A 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 27, 2022 (edit).
© 2007-2023 Sam Allen.