What is KeyError in Python? How to Handle Them?

While operating on the dictionaries in the Python programming language, the user might encounter KeyErrors. In python, Keyerrors usually occur when the coder tries to access an item in a particular dictionary, which is not present in the dictionary.

Here, we will try to explain to you about KeyError, its occurrence, how you can deal with it, and how to avoid having this error while working in dictionaries in Python.

What is a Python Dictionary?

Before we dig deeper into the KeyError python, it is necessary to know about how dictionaries work in the python language and how they are declared and used.

Dictionary in python is a random collection of values (data type), similar to a list or a set. But it is not like any other data type available in this programming language. The dictionary holds key-value pairs in it, which resemble a map.

The respective keys are required to be unique and are immutable data types such as strings and integers. But the value elements in the key-value pairs are not required to be unique, duplicate values are acceptable.

Here is an example of declaring a dictionary in the python programming language –

example_dict {

“coder”: “aman”

“example”: “dictionary”

“language”: “python”

}

In this example – (“language”: “python”) is a key-value pair. In which “language” is the key and “python” is the value. Keys appear before a colon in the dictionary.

What are KeyErrors in Python?

KeyErrors appear when you try to access a key in a dictionary, which are not available in that dictionary. And as python can not return a value for the key that does not even exist in the dictionary.

Let’s understand this concept of KeyErrors by using an example

dict {

“name”: “your name”

“problem”: “KeyErrors”

“language”: “python”

}

In this example, “name”, “problem” and “language” are the available keys in the given dictionary. But if we try to retrieve the value of the key “solution”, by using the code below –

print(dict[“solution”])

The code will return the KeyError as given below:

KeyError: ‘solution’

The Error simply tells us that the key we specified does not exist in the python dictionary. “solution” was the missing key in this example.

How to Handle Python KeyError Exceptions?

There are several handling mechanisms available for a KeyError in the python programming language. Let us discuss some of these keyerror handling mechanisms here

Using the ‘if and else’ Statement

With help of the if & else statement, lets you examine if a certain key is available or not in a specific dictionary before you access that value. By using this statement, one can prevent the keyError.

The code for the ‘if and else’ statement used to handle the python keyerror look like the one given below:

//List of fruits with their respective prices.

price = {‘Mango’: 120, ‘Apple’: 80, ‘Watermelon’: 30}

print(“The price list is:”, price)

fruit = “Kiwi”

if fruit in price.fruit():

   print(price[fruit])

else:

   print(“{} prices are not known”.format(fruit))

The result of the above code –

The price list is: {‘Mango’: 120, ‘Apple’: 80, ‘Watermelon’: 30}

Kiwi prices are not known.

In the above code, python will check if the entered key “kiwi” is present inside the “price” dictionary. In case the key exists in that particular dictionary, the If statement is executed and the code will print the price of that fruit (key). In case the key is absent from the desired dictionary, the else statement will be executed, telling that the key does not exist in the dictionary.

Hence, this is how the code helps you find out if you have entered the right key and eventually prevents the KeyError from occurring. The only issue with the use of the If and else statement is that you have to examine If a given key is available in the dictionary every time you enter a new key.

These tedious steps can be reduced with the use of the get() method to check the key values in the dictionary.

How to Use the Get() Method?

When the get() method is used on a dictionary, it will take an optional value alongside the given key as its input. And in case the entered key is available in the dictionary, then the get() will use the value associated with that key.

But in the case of KeyError, or when the entered key is absent from the dictionary, an optional value is evoked. If no optional value is entered while writing the python code, the output will show the default value of the output, which is “None”.

Let’s understand the get() method by using an example –

my_rig = { “chip”: “i5-10th-Gen”, “price”: 35000, “RAM”: “8GB” }

print(“The computer rig is:”, my_rig)

component = RAM

print(“The {} for this computer is {}.”.format(component, my_rig[component, not available]))

Output/result for the code is

The computer rig is: { “chip”: “i5-10th-Gen”, “price”: 35000, “RAM”: “8GB” }

The RAM for this computer is 8GB.

Now using a key that is not present in the python dictionary –

component = GPU

print(“The {} for this computer is {}.”.format(component, my_rig[component, not available]))

Output

The GPU for this computer is not available.

In case of no optional value, the code will print “None” in the place of “not available”

Using Try & Except Blocks

Try and except block is another handling mechanism available to avoid KeyError, while writing in python.

In this method, we will try to run a specific code with the provided key present in try blocks. If that specific code can not run due to an error, our code will raise a custom error from the Except block, according to the exception you have stated.

Let’s clarify this try and except blocks method by using an example –

age = {‘Mina’: 14, ‘Soni’: 19, ‘Rahul’: 24}

print (“The age of siblings is:”, age)

name = Rani

try:

   print(“The age of {} is {}.”.format(name,age[name]))

except KeyError:

   print(“Name is not available in the list”)

Output

The dictionary is: {‘Mina’: 14, ‘Soni’: 19, ‘Rahul’: 24}

Name is not available in the list

Conclusion

These errors are normal while using the Python language. Now you know how Python’s KeyError exception occurs and how to deal with them. We hope this article was informative and helped in your python programming journey.

Leave a Comment