Handle Python KeyError Exceptions 

While working on a data-cleaning project for a U.S.-based retail company, I ran into a frustrating issue, a Python KeyError. If you’ve worked with Python dictionaries, you’ve probably seen this error pop up at least once. It usually happens when you try to access a key that doesn’t exist.

At first, it can seem confusing, especially when your code looks perfectly fine. But once you understand what causes a KeyError and how to handle it properly, it becomes second nature.

In this tutorial, I’ll walk you through everything I’ve learned about handling KeyError in Python over my 10+ years of experience. I’ll show you multiple methods, from using try-except to get() and even defaultdict.

What Is a Python KeyError?

A KeyError in Python occurs when you try to access a dictionary key that doesn’t exist. For example, if you have a dictionary of U.S. states and their abbreviations, and you try to access a key that isn’t there, Python will raise a KeyError.

Here’s a simple example:

states = {"California": "CA", "Texas": "TX", "New York": "NY"}

# Trying to access a key that doesn't exist
print(states["Florida"])

When you run this code, Python throws:

KeyError: 'Florida'

This happens because “Florida” is not a key in the dictionary. So how do we fix this? Let’s look at some practical ways to handle it.

Method 1 – Handle Python KeyError Using Try-Except

The most common and Pythonic way to handle KeyError is by using a try-except block. This method allows your code to continue running even if a key is missing, instead of crashing.

Here’s how I usually do it:

states = {"California": "CA", "Texas": "TX", "New York": "NY"}

try:
    print(states["Florida"])
except KeyError:
    print("The key 'Florida' does not exist in the dictionary.")

When you run this, instead of an error, you’ll see:

The key 'Florida' does not exist in the dictionary.

You can see the output in the screenshot below.

python keyerror

This approach is great when you expect that some keys might be missing, for example, when reading data from a large JSON file or API response.

Pro Tip:
You can also use the except KeyError as e: syntax to capture the missing key and display it dynamically.

try:
    print(states["Florida"])
except KeyError as e:
    print(f"KeyError: The key '{e}' was not found.")

Method 2 – Use the Python Dictionary get() Method

Another clean way to avoid a KeyError in Python is by using the get() method. This method returns None (or a default value you specify) if the key doesn’t exist, instead of raising an error.

Here’s an example:

states = {"California": "CA", "Texas": "TX", "New York": "NY"}

abbreviation = states.get("Florida")
print(abbreviation)

Output:

None

You can see the output in the screenshot below.

keyerror python

If you want to return a custom message instead of None, simply add a second argument to get():

abbreviation = states.get("Florida", "Not Found")
print(abbreviation)

Output:

Not Found

This method is particularly useful when you’re iterating through a large dataset and want to safely access keys without worrying about KeyErrors.

Method 3 – Use Python defaultdict from collections

If you often deal with missing keys, the defaultdict from Python’s collections module can be a lifesaver. It automatically assigns a default value to any missing key.

Here’s how I use it:

from collections import defaultdict

states = defaultdict(lambda: "Unknown")
states["California"] = "CA"
states["Texas"] = "TX"

print(states["Florida"])

Output:

Unknown

You can see the output in the screenshot below.

key error python

This method is ideal when you’re processing large datasets or logs and want to ensure that missing keys don’t break your program.

Method 4 – Check if a Key Exists Before Accessing It

Sometimes, the simplest solution is to check if the key exists before using it.

You can do this using the in keyword.

states = {"California": "CA", "Texas": "TX", "New York": "NY"}

if "Florida" in states:
    print(states["Florida"])
else:
    print("Key not found.")

Output:

Key not found.

You can see the output in the screenshot below.

python key error

This approach is efficient when you only need to access a few keys and want to control how missing ones are handled.

Method 5 – Handle Nested Dictionary KeyError in Python

When working with nested dictionaries, KeyErrors can become tricky.

For example:

usa = {
    "California": {"Capital": "Sacramento"},
    "Texas": {"Capital": "Austin"}
}

print(usa["Florida"]["Capital"])

This will raise:

KeyError: 'Florida'

To handle this safely, combine get() methods:

# Safe way to access nested keys
capital = usa.get("Florida", {}).get("Capital", "Unknown")
print(capital)

Output:

Unknown

This ensures your code doesn’t crash, even if multiple levels of keys are missing.

Real-World Example: Handling KeyError in JSON Data

Let’s consider a real-world scenario, parsing JSON data from a U.S. weather API. Sometimes, the API might not include all expected keys, and your code can throw a KeyError.

Here’s how I handle it:

weather_data = {
    "city": "New York",
    "temperature": 68,
    # "humidity" key is missing
}

try:
    print(f"Humidity: {weather_data['humidity']}%")
except KeyError:
    print("Humidity data is not available for this location.")

Output:

Humidity data is not available for this location.

Alternatively, you can use get() for a cleaner approach:

humidity = weather_data.get("humidity", "Not Available")
print(f"Humidity: {humidity}")

Output:

Humidity: Not Available

Both methods work great depending on your use case.

Method 6 – Avoid KeyError When Updating or Deleting Keys

Another common situation where KeyErrors occur is when updating or deleting dictionary keys.

For example:

states = {"California": "CA", "Texas": "TX"}

del states["Florida"]

This raises:

KeyError: 'Florida'

To avoid this, always check if the key exists before deleting:

if "Florida" in states:
    del states["Florida"]
else:
    print("Key 'Florida' not found.")

Or use the pop() method with a default value:

states.pop("Florida", None)

This removes the key if it exists and does nothing otherwise.

Bonus Tip – Logging KeyError in Python

When working in production or debugging large Python applications, it’s good practice to log KeyErrors instead of just printing them.

import logging

logging.basicConfig(level=logging.INFO)

data = {"Name": "John"}

try:
    print(data["Age"])
except KeyError as e:
    logging.error(f"Missing key: {e}")

Output:

ERROR:root:Missing key: 'Age'

This helps you track missing keys without interrupting your program’s execution.

Handling KeyError in Python is all about writing defensive and clean code. Over the years, I’ve learned that using try-except is great for one-off lookups, while get() and defaultdict are perfect for larger data-processing tasks.

If you’re dealing with APIs, JSON, or user input, always assume that some keys might be missing and handle them gracefully. By mastering these techniques, you’ll make your Python programs more robust, reliable, and professional.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.