KeyError: 0 in a Python dictionary

In this tutorial, we will explore how to handle the Python dictionary KeyError: 0 The Python “KeyError: 0” exception is caused when we try to access a ‘0’ key in a dictionary. There are different methods to do so, we will see them one by one with examples.

Python Dictionary KeyError: 0

A common error in Python that many beginners and even advanced users encounter is the notorious KeyError 0. This error is raised when we try to access a key that doesn’t exist in a dictionary.

In this example, we’re trying to access a key 0 in a dictionary where the keys are states’ names in a Python dictionary.

usa_states = {'California': 'Sacramento', 'New York': 'Albany', 'Texas': 'Austin'}
print(usa_states[0])

The output as we can see: Python throws a KeyError: 0, telling us there is no such key.

Traceback (most recent call last):
  File "C:\Users\USER\PycharmProjects\pythonProject\TS\main.py", line 2, in <module>
    print(usa_states[0])
          ~~~~~~~~~~^^^
KeyError: 0
How to handle KeyError 0 in python dictionary

Handling KeyError: 0 in a Python dictionary

There are several different ways we can prevent or handle a KeyError:0 in a Python dictionary. Here are some of the most common and effective methods:

  • Using the get() method
  • Using an if-else conditional statement

Method-1: Using the get() method in the Python dictionary

A safer way to retrieve a value from a dictionary is to use the get() method in Python. As this method does not raise a KeyError if the key is not found. Instead, it returns None or a default value, when mentioned.

Here’s an example using popular American sports data as stored in a Python dictionary:

usa_sports = {'baseball': 'New York Yankees', 'basketball': 'Los Angeles Lakers', 'football': 'Dallas Cowboys'}
print(usa_sports.get(0))

The output of the code, if no default value is mentioned, is:

None

We can also provide a default value to the Python get() method which it will return if the key is not found. Let’s extend the previous example:

print(usa_sports.get(0, 'Sport not found'))

Output, In this case, if the key 0 does not exist, the string ‘Sport not found’ is printed.

Sport not found
How to handle KeyError 0 in python dictionary using get()

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

Read How to remove a key without an error in the Python dictionary

Method-2: Using an if-else conditional statement in the Python dictionary

We will use the if statement to check whether the key exists in the dictionary, if not present, returns it with the else statement to not show KeyError in Python.

Here, we use the names of famous U.S. cities and their shortcuts as Python dictionary data:

usa_cities = {'LA': 'Los Angeles', 'NY': 'New York', 'CA': 'Chicago'}
if 0 in usa_cities:
    print(usa_cities[0])
else:
    print('Key not found')

The output will be ‘Key not found’, as 0 is not a key in the dictionary.

Key not found
How to handle KeyError 0 in python dictionary using if-else

This way, we can check if the key exists in the Python dictionary before trying to access it, using the if-else statement.

Conclusion:

KeyError: 0 can be a headache for Python developers, but with the right techniques, we can handle this, gracefully. Either by using the safe get() method to provide a default value or by first checking if the key exists, using if-else conditional statements.

You may like to read: