HomeSearch

Python KeyError Fix: Use Dictionary get

This Python article shows how to fix the KeyError. The KeyError is encountered when using a dictionary.

KeyError.

A dictionary can cause a KeyError to occur. This happens due to incorrect use of the dictionary. We can prevent the KeyError in most cases by using the get() method on the dictionary.

Example.

This program causes a KeyError to be thrown. The dictionary contains just three entries—these have the keys "a", "b" and "c". We try to access a key "d" but it does not exist. And a KeyError is encountered.

Next,

we trap the KeyError in a try-except construct. We print an error message in the except-block. And finally, after handling exceptions, we access key "d" with the get() method. This is safe. No exception is raised.Error
Python program that handles KeyError # 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")) Output KeyError encountered None

A KeyError is avoidable

in Python programs. We fix the problem by using a safe method, such as get(), instead of directly accessing the key. We can only directly access a key if we are sure it exists.

Also: If any direct accesses occur in your program, using a try-except block may be worthwhile if your code is new or untested.

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. We used a try-except statement. And we replaced the value access with a get() method call.Dictionary
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.