Fix the Key Error in a Dictionary in Python

Dictionary is a scalable data structure available in Python. It stores data in the form of key-value pairs where a key can be any hashable and immutable object and value can be anything; a list, a tuple, a dictionary, a list of objects, and so on.

Using keys, we can access the values these keys are pointing to. If a non-existent key is given to a dictionary, it throws a KeyError exception. In this article, we will learn how to handle this exception in Python.

Fix the KeyError Exception in a Dictionary in Python

To resolve the KeyError exception, one can check if the key exists in the dictionary before accessing it. The keys() method returns a list of keys inside the dictionary. Before accessing the value at a key, it is recommended to check if the key exists in this list if you are unsure about its existence. The following Python code depicts the same.

data = {
    "a": 101,
    "b": 201,
    "c": 301,
    "d": 401,
    "e": 501,
}
keys = ["a", "e", "r", "f", "c"]

for key in keys:
    if key in data.keys():
        print(data[key])
    else:
        print(f"'{key}' not found.")

Output:

101
501
'r' not found.
'f' not found.
301

Apart from the approach discussed above, one can also use a try...except block to catch the KeyError exception or any exception. Refer to the following Python code for the same.

data = {
    "a": 101,
    "b": 201,
    "c": 301,
    "d": 401,
    "e": 501,
}
keys = ["a", "e", "r", "f", "c"]

for key in keys:
    try:
        print(data[key])
    except:
        print(f"'{key}' not found.")

Output:

101
501
'r' not found.
'f' not found.
301

The code under the except block will get executed if a KeyError exception occurs.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Error

  • Address Already in Use Error in Python
  • Resolve the NameError: Global Name __File__ Is Not Defined Error in Python
  • Handle the Python Assertion Error and Find the Source of Error
  • MemoryError in Python