A KeyError
in Python occurs when you attempt to access a dictionary key that does not exist. It is a common exception that indicates the key you’re trying to access is not found in the dictionary. This guide will help you understand the KeyError
and how to handle it.
1. Understanding KeyError
A KeyError
is raised when a dictionary is accessed with a key that is not present in the dictionary. Here’s an example:
my_dict = {'name': 'Alice', 'age': 25}
# Accessing an existing key
print(my_dict['name']) # Output: Alice
# Accessing a non-existing key
print(my_dict['address']) # Raises KeyError: 'address'
2. Handling KeyError with try-except
You can handle a KeyError
using a try-except
block to catch the exception and handle it gracefully:
my_dict = {'name': 'Alice', 'age': 25}
try:
print(my_dict['address'])
except KeyError:
print("Key not found in the dictionary.")
3. Using dict.get()
Method
The dict.get()
method allows you to access dictionary keys without raising a KeyError
. If the key is not found, it returns a default value:
my_dict = {'name': 'Alice', 'age': 25}
# Accessing an existing key
print(my_dict.get('name')) # Output: Alice
# Accessing a non-existing key with a default value
print(my_dict.get('address', 'Not Available')) # Output: Not Available
4. Checking if a Key Exists
Before accessing a key, you can check if it exists in the dictionary using the in
keyword:
my_dict = {'name': 'Alice', 'age': 25}
if 'address' in my_dict:
print(my_dict['address'])
else:
print("Key not found in the dictionary.")
5. Example: Safe Dictionary Access
Here’s an example demonstrating safe access to a dictionary:
def safe_access(dictionary, key):
return dictionary.get(key, 'Key not found')
my_dict = {'name': 'Alice', 'age': 25}
print(safe_access(my_dict, 'name')) # Output: Alice
print(safe_access(my_dict, 'address')) # Output: Key not found
6. Summary
A KeyError
occurs when trying to access a dictionary key that does not exist. You can handle this exception using try-except
blocks, the dict.get()
method, or by checking if the key is present before accessing it. Understanding and handling KeyError
helps make your code more robust and user-friendly.