How to handle KeyError with Try-Except in a Python dictionary

In this Python tutorial, we will see how to handle KeyError with Try-Except in a Python dictionary with different examples.

A Python dictionary is one of the data structures. It is used to store data in key-value pairs. It provides us with an efficient way of organizing and retrieving data, but what happens when we try to retrieve a value using a key that doesn’t exist in the dictionary? we get a KeyError.

What is a KeyError in a Python dictionary?

In a Python dictionary, a KeyError typically arises when you attempt to access a dictionary key that doesn’t exist. This can lead to program crashes if not handled correctly. However, Python provides a graceful way to handle such exceptions using the try-except block.

For example, we have all the US states and their capital data stored in the form of a Python dictionary.

us_states = {
    'Alabama': 'Montgomery',
    'Alaska': 'Juneau',
    'Arizona': 'Phoenix',
    'Arkansas': 'Little Rock',
    'California': 'Sacramento',
    # ...
    # All other states
    # ...
    'Wyoming': 'Cheyenne'
}

print(us_states['Ontario'])

The output is showing KeyError Because ‘Ontario‘ is a province in Canada, not a state in the USA. So, the Python interpreter raises a KeyError because it cannot find this key in the us_states dictionary.

Traceback (most recent call last):
  File "C:\Users\USER\PycharmProjects\pythonProject\TS\main.py", line 13, in <module>
    print(us_states['Ontario'])
          ~~~~~~~~~^^^^^^^^^^^^
KeyError: 'Ontario'
How to handle KeyError in Python dictionary with try-except

Handling KeyError with Try-Except in a Python dictionary

Python provides us with the try-except block to handle exceptions. We can apply this to handle KeyError.

We keep the Python block of code that can give any error in the try block and we handle the error(if any occurred) with the error name in except block, which will then execute when any exception happens.

In the previous example how we will use the try-except block to handle the KeyError:

us_states = {
    'Alabama': 'Montgomery',
    'Alaska': 'Juneau',
    'Arizona': 'Phoenix',
    'Arkansas': 'Little Rock',
    'California': 'Sacramento',
    # ...
    # All other states
    # ...
    'Wyoming': 'Cheyenne'
}
def state_capital_lookup():
    state = input("Enter a U.S. state: ")

    try:
        print(f"The capital of {state} is {us_states[state]}.")
    except KeyError:
        print("The state you entered is not in our database. Please enter a valid U.S. state.")

state_capital_lookup()

The Output will be :

In this code, we are using the Python input() function to receive input from the user. The try block attempts to find the user-provided state in the us_states dictionary. If the state is not found, it raises a Python KeyError, which is then caught by the except block, and an error message is printed out to the user.

Enter a U.S. state: Ontario
The state you entered is not in our database. Please enter a valid U.S. state.
How to handle KeyError with try-except block in python dictionary

The Python code didn’t show any error, as it was handled by the try-except block.

Note: if we don’t want any message to be printed, we can use the pass keyword in the except block.

Conclusion:

In conclusion, Errors and exceptions are common in any program, and they are not necessarily bad. They alert us to problems that need our attention. Python’s try-except block handles these exceptions. By learning how to handle KeyError with the try-except block in Python dictionaries.

You may also like to read: