KeyError in Python – How to Fix Dictionary Error

When I was working on a customer data analysis project for a retail chain when I encountered a frustrating KeyError that crashed my entire script. The issue was that I was trying to access dictionary keys that didn’t always exist in the dataset.

KeyError is one of the most common exceptions Python developers face when working with dictionaries. It occurs when you try to access a key that doesn’t exist in the dictionary.

In this guide, I’ll share four proven methods to handle and fix KeyError exceptions in Python.

What is KeyError in Python?

KeyError is a built-in Python exception that occurs when you attempt to access a dictionary key that doesn’t exist. This exception belongs to the LookupError family and can halt your program execution if not handled properly.

Here’s a simple example that demonstrates when KeyError occurs:

# Sample customer data
customer_data = {
    'name': 'John Smith',
    'email': 'john.smith@email.com',
    'city': 'New York'
}

# This will raise KeyError
print(customer_data['phone'])  # KeyError: 'phone'

You can see the error message in the screenshot below.

python keyerror

The error happens because the ‘phone’ key doesn’t exist in our dictionary.

Method 1 – Use Try-Except Block

The most fundamental way to handle KeyError is using a try-except block. This approach allows you to catch the exception and provide alternative behavior.

# Sample employee database
employees = {
    'emp001': {'name': 'Alice Johnson', 'department': 'Engineering'},
    'emp002': {'name': 'Bob Wilson', 'department': 'Marketing'},
    'emp003': {'name': 'Carol Davis', 'department': 'Sales'}
}

def get_employee_info(emp_id):
    try:
        employee = employees[emp_id]
        return f"Employee: {employee['name']}, Department: {employee['department']}"
    except KeyError:
        return f"Employee ID {emp_id} not found in database"

# Test the function
print(get_employee_info('emp001'))  # Employee: Alice Johnson, Department: Engineering
print(get_employee_info('emp999'))  # Employee ID emp999 not found in database

You can refer to the screenshot below to see the output:

keyerror python

This method provides complete control over error handling and allows you to define custom responses when keys don’t exist.

Method 2 – Use the get() Method

Python’s get() method is my go-to solution for handling missing keys gracefully. It returns None (or a specified default value) instead of raising KeyError.

# US state population data (in millions)
state_population = {
    'California': 39.5,
    'Texas': 29.1,
    'Florida': 21.5,
    'New York': 19.3,
    'Pennsylvania': 12.8
}

def get_population_info(state_name):
    population = state_population.get(state_name)

    if population:
        return f"{state_name} has a population of {population} million"
    else:
        return f"Population data for {state_name} is not available"

# Using get() with default value
def get_population_with_default(state_name):
    population = state_population.get(state_name, "Unknown")
    return f"{state_name}: {population}"

# Test both approaches
print(get_population_info('California'))  # California has a population of 39.5 million
print(get_population_info('Alaska'))      # Population data for Alaska is not available

print(get_population_with_default('Texas'))   # Texas: 29.1
print(get_population_with_default('Alaska'))  # Alaska: Unknown

You can refer to the screenshot below to see the output:

key error python

Python’s get() method is clean, readable, and prevents KeyError exceptions while allowing you to specify default values.

Method 3 – Use the in Operator for Key Checking

Before accessing Python dictionary keys, you can check their existence using the in operator. This preventive approach stops KeyError before it occurs.

# Product inventory system
inventory = {
    'laptop': {'price': 999.99, 'stock': 15},
    'smartphone': {'price': 699.99, 'stock': 32},
    'tablet': {'price': 299.99, 'stock': 8},
    'headphones': {'price': 149.99, 'stock': 25}
}

def check_product_availability(product_name):
    if product_name in inventory:
        product = inventory[product_name]
        if product['stock'] > 0:
            return f"{product_name.title()} is available. Price: ${product['price']}, Stock: {product['stock']}"
        else:
            return f"{product_name.title()} is out of stock"
    else:
        return f"{product_name.title()} is not in our inventory"

def bulk_price_check(products):
    results = []
    for product in products:
        if product in inventory:
            price = inventory[product]['price']
            results.append(f"{product}: ${price}")
        else:
            results.append(f"{product}: Not available")
    return results

# Test the functions
print(check_product_availability('laptop'))     # Laptop is available. Price: $999.99, Stock: 15
print(check_product_availability('monitor'))    # Monitor is not in our inventory

products_to_check = ['laptop', 'mouse', 'smartphone', 'keyboard']
print(bulk_price_check(products_to_check))
# ['laptop: $999.99', 'mouse: Not available', 'smartphone: $699.99', 'keyboard: Not available']

Using the in operator provides explicit key validation and makes your code more readable by clearly showing your intention to check for key existence.

Method 4 – Use setdefault() Method

Python’s setdefault() method returns the value of a key if it exists, or sets and returns a default value if the key doesn’t exist. This is particularly useful when building dictionaries dynamically.

# Customer order tracking system
customer_orders = {}

def add_customer_order(customer_id, product, quantity):
    # setdefault ensures the customer has an order list
    customer_orders.setdefault(customer_id, []).append({
        'product': product,
        'quantity': quantity
    })

def get_customer_order_count(customer_id):
    orders = customer_orders.setdefault(customer_id, [])
    return len(orders)

def calculate_customer_stats():
    stats = {}
    for customer_id, orders in customer_orders.items():
        total_items = sum(order['quantity'] for order in orders)
        stats.setdefault('total_customers', 0)
        stats.setdefault('total_orders', 0)
        stats.setdefault('total_items', 0)

        stats['total_customers'] = len(customer_orders)
        stats['total_orders'] += len(orders)
        stats['total_items'] += total_items

    return stats

# Test the system
add_customer_order('CUST001', 'Laptop', 1)
add_customer_order('CUST001', 'Mouse', 2)
add_customer_order('CUST002', 'Keyboard', 1)
add_customer_order('CUST003', 'Monitor', 1)

print("Customer Orders:", customer_orders)
print("Customer CUST001 order count:", get_customer_order_count('CUST001'))  # 2
print("Customer CUST999 order count:", get_customer_order_count('CUST999'))  # 0
print("Customer Stats:", calculate_customer_stats())

The setdefault() method in Python is perfect for initializing dictionary values and avoiding KeyError when building complex data structures.

Conclusion

Python’s get() method remains my most frequently used approach for simple key lookups, while defaultdict is invaluable for complex data structures that need automatic initialization.

For production applications handling customer data or financial information, I always recommend using try-except blocks with custom error messages. This approach provides the clarity and error tracking necessary for debugging and maintenance.

You may also 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.