How to Fix the Key Error in a Dictionary in Python

Vaibhav Vaibhav Feb 02, 2024
How to 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.

Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

Related Article - Python Error