
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Catch KeyError Exception in Python
In Python, a KeyError exception occurs when a dictionary key that does not exist is accessed. This can be avoided by using proper error handling with the try and except blocks, which can catch the error and allow the program to continue running.
Understanding KeyError in Python
A KeyError is raised when you try to access a key that doesn't exist in a dictionary. It is one of the built-in exceptions that can be handled by Python's try and except blocks.
Example: Accessing a non-existent key
In this example, we are attempting to access a key that does not exist in the dictionary, leading to a KeyError -
my_dict = {"apple": 1, "banana": 2} print(my_dict["orange"])
The output obtained is -
Traceback (most recent call last): ... KeyError: 'orange'
Catching KeyError with try and Except
To catch a KeyError and prevent the program from crashing, use a try block to attempt the operation and an except block to handle the exception if it occurs.
Example
In this example, we use a try and except block to catch a KeyError and handle it -
my_dict = {"apple": 1, "banana": 2} try: print(my_dict["orange"]) except KeyError: print("Key not found.")
Following is the output obtained -
Key not found.
Providing a custom Error Message
You can provide a custom error message when catching a KeyError to give more specific details about the exception.
Example
In this example, we are using a custom error message to indicate which key was missing -
my_dict = {"apple": 1, "banana": 2} try: print(my_dict["orange"]) except KeyError as e: print(f"Key '{e.args[0]}' not found in the dictionary.")
We get the output as shown below -
Key 'orange' not found in the dictionary.
Using the get() method to avoid KeyError
Another way to avoid a KeyError is by using the get() method. This method returns None if the key is not found, instead of raising an exception.
Example
In this example, we use the get() method to retrieve a value without raising a KeyError -
my_dict = {"apple": 1, "banana": 2} print(my_dict.get("orange", "Key not found"))
The result produced is as follows -
Key not found
Handling KeyError with a default Value
You can also handle missing keys by setting default values using the defaultdict class from the collections module. This automatically assigns a default value to missing keys.
Example
In this example, we use a defaultdict to handle missing keys and assign a default value of 0 -
from collections import defaultdict my_dict = defaultdict(int) my_dict["apple"] = 1 print(my_dict["orange"]) # Defaults to 0
We get the output as shown below -
0
When to use try-except for KeyError
Using a try-except block to handle a KeyError is useful when you are not sure whether a key exists in the dictionary. But for better performance, it is better to use the get() method or the in keyword to first of all, check if the key exists.
Example: Using 'in' to check for key existence
In this example, we use the in keyword to check if a key exists before trying to access it, avoiding the need for exception handling -
my_dict = {"apple": 1, "banana": 2} if "orange" in my_dict: print(my_dict["orange"]) else: print("Key not found.")
The output is -
Key not found.