You might have encountered KeyError while working with dictionaries in python. In this article, we will discuss what a KeyError is, how it occurs and how we can avoid a KeyError while working with a python dictionary.
What is Python KeyError ?
In simple terms, KeyError is an exception raised by a python program when we try to access a value from a dictionary with a key that is not present in the dictionary.
For example, look at the following program. Here the dictionary myDict has keys 1, 2, and 3 with values 1, 4, and 9 associated with the keys. When we try to access the dictionary with a key 4, the program raises a KeyError. This is due to the reason that 4 is not present in the dictionary as a key.
myDict = {1: 1, 2: 4, 3: 9}
print("The dictionary is:", myDict)
print(myDict[4])
Output:
The dictionary is: {1: 1, 2: 4, 3: 9}
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string.py", line 3, in <module>
print(myDict[4])
KeyError: 4
How to avoid Python KeyError exceptions?
There are various ways to avoid KeyError exceptions. Let us discuss them one by one.
Using If else statement
Using the if else statement, we can check if a given key is present in the keys of the dictionary before accessing the value. It helps us to avoid the KeyError exception.
myDict = {1: 1, 2: 4, 3: 9}
print("The dictionary is:", myDict)
key = 4
if key in myDict.keys():
print(myDict[key])
else:
print("{} not a key of dictionary".format(key))
Output:
The dictionary is: {1: 1, 2: 4, 3: 9}
4 not a key of dictionary
The drawback here is that each time we have to check if a given key is present in the keys of the dictionary. This extra work can be avoided if we use the get() method to access values from the dictionary.
Using the get() method
The get() method, when invoked on a dictionary, takes the given key and an optional value as input. If the given key is present in the dictionary, it gives the associated value to the key as output as follows.
myDict = {1: 1, 2: 4, 3: 9}
print("The dictionary is:", myDict)
key = 3
print("Key is:",key)
print("Value associated to the key is:",myDict.get(key))
Output:
The dictionary is: {1: 1, 2: 4, 3: 9}
Key is: 3
Value associated to the key is: 9
When the given key is not present in the dictionary, it returns None if no optional value is passed.
myDict = {1: 1, 2: 4, 3: 9}
print("The dictionary is:", myDict)
key = 4
print("Key is:",key)
print("Value associated to the key is:",myDict.get(key))
Output:
The dictionary is: {1: 1, 2: 4, 3: 9}
Key is: 4
Value associated to the key is: None
If we pass an optional value as input to the get() method, it returns the value when the given key is not present in the dictionary.
myDict = {1: 1, 2: 4, 3: 9}
print("The dictionary is:", myDict)
key = 4
print("Key is:",key)
print("Value associated to the key is:",myDict.get(key,16))
Output:
The dictionary is: {1: 1, 2: 4, 3: 9}
Key is: 4
Value associated to the key is: 16
Using Try Except
We can use python try except blocks to handle the KeyError exception. For that, we will execute the code to access the value using the given key in the try block and will handle the exception in the except block as follows.
myDict = {1: 1, 2: 4, 3: 9}
print("The dictionary is:", myDict)
key=4
print("Key is:",key)
try:
val=myDict[key]
print("Value associated to the key is:",val)
except KeyError:
print("Key not present in Dictionary")
Output:
The dictionary is: {1: 1, 2: 4, 3: 9}
Key is: 4
Key not present in Dictionary
Conclusion
In this article, we have discussed KeyErrors and the ways to handle them. To learn more about python programming, you can read this article on list comprehension. You may also like this article on the linked list in Python.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.