How to Solve KeyError in Python

To solve KeyError in Python, use the try-except block and ensure that the key exists in the dictionary. The KeyError occurs when we try to access a key element within a dictionary that does not exist.

Python Dictionary contains key-value pairs. We can call the elements by using the key.

KeyError in Python

KeyError in Python is raised when the key does not exist, and we are trying to get the value by that key. Dictionaries can be created using the dict() function or can be created simply by using {} (Curly braces). Keys are unique in the dictionary. Therefore, we can change the value or get the value using its key.

Example

dic = {"name": "Yadhav", "age": 25,
       "email": "yadhav@gmail.com", 
       "department": "CSE"}

print(dic["name"]) # Yadhav
print(dic["age"]) # 25
print(dic["email"]) # yadhav@gmail.com
print(dic["department"]) # CSE
print(dic["Phone_number"])

Output

Yadhav
25
yadhav@gmail.com
CSE

Traceback (most recent call last):
File "/Users/krunallathiya/Desktop/Code/R/data.py", line 8, in <module>
print(dic["Phone_number"])

KeyError: 'Phone_number'

You can see from the output that it can not find the “Phone_number” key, and hence it throws a KeyError.

There is no key with the name Phone_number, which creates an error known as the KeyError. This is because the calling key is not present in the dictionary. We can use if-else or try-except to check whether the key is present or not in the dictionary. Using that, we can call if the key is there; else, we can say that the key is not present.

Example

dict = {"name": "Yadhav", "age": 25, "email": "yadhav@gmail.com", "department": "CSE"}

if("name" in dict):
  print(dict["name"])
else:
  print("Key is not present")
  # Yadhav is printed.

if("city" in dict):
  print(dict["city"])
else:
  print("Key city is not present")

Output

Yadhav
Key city is not present

You can see that the “name” key exists in the dictionary; that’s why it returns the value, but the “city” key does not exist, and that’s why else block is executed.

Solve KeyError using try-except

The try-except block handles the KeyError very well. First, we check whether the key is present in the dictionary in the try block. If it exists, we can print the value in the try block. If the key does not exist, we will handle it using except block. We can use KeyError as except method to catch the exception.

dic = {"name": "Yadhav", "age": 25,
       "email": "yadhav@gmail.com", "department": "CSE"}

try:
 print(dic["name"])
 print(dic["age"])
 print(dic["Phone_number"])

except KeyError:
 print("Key does not exist")

Output

Yadhav
25
Key does not exist

In this example, name and age results will be displayed. However, the Phone_number Key does not exist in the dictionary, so the KeyError exception is raised. In the exception block, we catch the exception and print the message.

For the key Phone_number, the exception block prints the output as the Key does not exist.

Conclusion

The KeyError occurs while working with a dictionary because it has a key-value data structure. We can solve or handle the KeyError exception by using an if-else statement or try-except block.

That’s it for this tutorial.

See also

How to Solve MemoryError in Python

How to Solve NotImplementedError in Python

OverflowError: Python int too large to convert to C long

How to Solve EOFError in Python

TypeError: ‘str’ object is not callable in Python

Leave a Comment