How to catch KeyError Exception in Python?

In Python, a KeyError exception occurs when trying to access a dictionary key that does not exist. This can be handled using try-except blocks to prevent program crashes and provide graceful error handling.

Understanding KeyError in Python

A KeyError is raised when you attempt to access a key that doesn't exist in a dictionary. It's one of Python's built-in exceptions that can be caught and handled properly.

Example: Accessing a Non-existent Key

Here's what happens when trying to access a missing key ?

my_dict = {"apple": 1, "banana": 2}
print(my_dict["orange"])

The output obtained is ?

Traceback (most recent call last):
  File "<string>", line 2, in <module>
KeyError: 'orange'

Catching KeyError with try-except

Use a try-except block to catch KeyError and handle it gracefully ?

my_dict = {"apple": 1, "banana": 2}

try:
    print(my_dict["orange"])
except KeyError:
    print("Key not found.")
Key not found.

Providing Custom Error Messages

You can capture the exception object to provide more detailed error messages ?

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.")
Key 'orange' not found in the dictionary.

Alternative Approaches to Avoid KeyError

Using the get() Method

The get() method returns a default value instead of raising an exception ?

my_dict = {"apple": 1, "banana": 2}

# Using get() with default value
result = my_dict.get("orange", "Key not found")
print(result)

# Using get() without default (returns None)
result2 = my_dict.get("orange")
print(f"Result: {result2}")
Key not found
Result: None

Using the 'in' Operator

Check if a key exists before accessing it ?

my_dict = {"apple": 1, "banana": 2}

if "orange" in my_dict:
    print(my_dict["orange"])
else:
    print("Key not found.")
Key not found.

Using defaultdict for Automatic Default Values

The defaultdict class automatically assigns default values to missing keys ?

from collections import defaultdict

# Create defaultdict with int (defaults to 0)
my_dict = defaultdict(int)
my_dict["apple"] = 1

print(f"Apple: {my_dict['apple']}")
print(f"Orange: {my_dict['orange']}")  # Automatically gets default value 0
Apple: 1
Orange: 0

Comparison of Methods

Method Performance Best For
try-except Slower if exceptions occur frequently When exceptions are rare
get() Fast Simple default value handling
in operator Fast When you need to check existence first
defaultdict Fast When you need automatic defaults

Conclusion

Use try-except for KeyError when exceptions are rare. For better performance with frequent missing keys, prefer get() method or check existence with in operator first.

Updated on: 2026-03-24T16:19:14+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements