KeyError in a nested Python dictionary

In this Python tutorial, we will see how to handle KeyError in a nested Python dictionary. There are several different methods to do so. We will see them one by one using some examples.

What is a KeyError in a nested Python Dictionary?

A Python nested dictionary has a dictionary as a value for its keys and A KeyError occurs when you attempt to access a Python dictionary key that does not exist.

This is quite common when dealing with nested dictionaries, where one or more levels might not contain the key we’re looking for. In this, we’ll discuss how to handle these Python dictionary KeyErrors effectively.

Let’s imagine a Python nested dictionary that holds information about various Hollywood actors and their films:

hollywood = {
    'Leonardo DiCaprio': {
        'movie': 'Inception',
        'year': 2010
    },
    'Tom Hanks': {
        'movie': 'Forrest Gump',
        'year': 1994
    }
}

print(hollywood['Johnny Depp']['movie'])

Output is: If we attempt to access a key that does not exist, Python will raise a KeyError because ‘Johnny Depp‘ does not exist in the dictionary.

Traceback (most recent call last):
  File "C:\Users\USER\PycharmProjects\pythonProject\TS\main.py", line 12, in <module>
    print(hollywood['Johnny Depp']['movie'])
          ~~~~~~~~~^^^^^^^^^^^^^^^
KeyError: 'Johnny Depp'
How to handle KeyError in nested python dict

Handling KeyError in a nested Python dictionary

We can handle these exceptions in the nested Python dictionary by:

  • Using try-except blocks
  • Using the dictionary’s get() method

which allows us to provide a default value if a key is not found.

Method-1: Handle the KeyError using the try-except block in a nested Python dictionary

One way to handle these exceptions is by using try-except blocks. Here, Python will ‘try’ to execute a block of code from the try block, and if it encounters an exception, it will ‘catch’ it and execute an alternate block of code from the Python except block.

let’s imagine a scenario in which we have a nested Python dictionary representing a selection of items available on an Amazon-like e-commerce platform. Each item has details like ‘price’ and ‘stock’ associated with it:

amazon_items = {
    'Echo Dot': {
        'price': 49.99,
        'stock': 1000
    },
    'Kindle Paperwhite': {
        'price': 129.99,
        'stock': 500
    }
}

try:
    print(amazon_items['iPhone 13']['price'])
except KeyError:
    print('Item not found in the store.')

Now, if a customer wants to know the price of an ‘iPhone 13’, we would try to access the price. However, ‘iPhone 13’ does not exist in the dictionary, and Python would raise a KeyError.

We can handle this exception by using a Python try-except block.

Output: However, the except block catches this exception and instead of the Python program terminating, it prints ‘Item not found in the store.’ This way, the user gets a meaningful message rather than an error.

Item not found in the store.
How to handle KeyError in nested python dict. using try-except

Note: If we don’t want any message to be printed, then we can use the Python pass keyword in the except block to just pass if any exception happens.

This way we use the try-except block method to simply handle the KeyError in a nested Python dictionary.

Method-2: Handling KeyError using the get() method in a nested Python dictionary

Another way to handle a KeyError is by using the Python dictionary’s get() method. This method allows us to provide a default value if a key is not found.

let’s consider a Python nested dictionary that holds information about various famous New York landmarks and their details and let’s say we want to find out when ‘Central Park’ was built.

However, since ‘Central Park’ does not exist in the dictionary, Python will raise a KeyError. We can handle this KeyError by using the get() method.

The Python get() method tries to retrieve the value for a specified key, and if it can’t find the key, it returns a default value(if provided) or None.

new_york_landmarks = {
    'Statue of Liberty': {
        'location': 'Liberty Island',
        'year_built': 1886
    },
    'Empire State Building': {
        'location': 'Midtown Manhattan',
        'year_built': 1931
    }
}

landmark_info = new_york_landmarks.get('Central Park', {})
year_built = landmark_info.get('year_built', 'Year not found.')
print(year_built)

Output: In this case, the first get() method tries to get the Python dictionary for ‘Central Park’. If ‘Central Park’ is not found, it returns an empty dictionary.

The second get() method then tries to get the ‘year_built’ from this dictionary. If ‘year_built’ is not a key in the dictionary (which it won’t be, because an Python empty dictionary was returned).

Year not found.
How to handle KeyError in nested python dict. using get()

This way we can use the get() method in the nested Python dictionary to handle the KeyError.

Conclusion:

Handling KeyErrors is fundamental to ensuring our Python code runs smoothly, especially when working with nested Python dictionaries. Both the try-except method and the get() method provide ways to do this, allowing us to provide a more seamless user experience.

You may also like to read: