KeyError: 3 exception in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

KeyError: 3 exception in Python #

The Python "KeyError: 3" exception is caused when we try to access a 3 key in a dictionary that doesn't contain the key. To solve the error, set the key in the dictionary before trying to access it or conditionally set it if it doesn't exist.

keyerror 3

Here is an example of how the error occurs.

main.py
my_dict = {1: ['a', 'b'], 2: ['c', 'd']} # ⛔️ KeyError: 3 print(my_dict[3])

We tried accessing a 3 key in a dictionary that doesn't contain it.

One way to solve the error is to set a value for the specific key before trying to access it.

main.py
my_dict = {1: ['a', 'b'], 2: ['c', 'd']} my_dict[3] = [] # 👈️ initialize key to empty list my_dict[3].append('e') my_dict[3].append('f') print(my_dict[3]) # 👉️ ['e', 'f']

We initialized the 3 key to an empty list in the example.

You can also check if the key doesn't exist in the dictionary before setting it.

main.py
my_dict = {1: ['a', 'b'], 2: ['c', 'd']} # ✅ set value for key if it doesn't exist if 3 not in my_dict: my_dict[3] = [] my_dict[3].append('e') my_dict[3].append('f') print(my_dict[3]) # 👉️ ['e', 'f']

We check if the 3 key doesn't exist in the dictionary and initialize its value to an empty list.

Use the dict.items() method if you need to iterate over a dictionary.

main.py
my_dict = {1: ['a', 'b'], 2: ['c', 'd'], 3: ['e', 'f']} for key, value in my_dict.items(): print(key, value) # 👉️ 1 ['a', 'b'], 2 ['c', 'd'], 3 ['e', 'f']

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

An alternative approach to avoid the "KeyError: 3" exception is to use the dict.get() method.

main.py
my_dict = {1: ['a', 'b'], 2: ['c', 'd']} print(my_dict.get(3)) # 👉️ None print(my_dict.get(3, 'default value')) # 👉️ 'default value'

The dict.get method returns the value for the given key if the key is in the dictionary, otherwise a default value is returned.

The method takes the following 2 parameters:

NameDescription
keyThe key for which to return the value
defaultThe default value to be returned if the provided key is not present in the dictionary (optional)

If a value for the default parameter is not provided, it defaults to None, so the get() method never raises a KeyError.

You can also use a try/except statement to handle the error.

main.py
my_dict = {1: ['a', 'b'], 2: ['c', 'd']} try: print(my_dict[3]) except KeyError: # 👇️ this runs print('key does not exist in dict') my_dict[3] = [] # 👈️ can initialize key if necessary

The KeyError exception gets handled by the except clause where you can initialize the 3 key if necessary.

You can also use the defaultdict class to avoid the error.

main.py
from collections import defaultdict my_dict = defaultdict(list) my_dict[3].append('e') my_dict[3].append('f') print(my_dict) # 👉️ defaultdict(<class 'list'>, {3: ['e', 'f']})

The defaultdict class takes a default_factory argument which it calls to provide a default value for the given key.

The value for the key is inserted in the dictionary and is returned.

We passed the list class to the constructor, so every time we try to access a key that doesn't exist, the list class is called without any arguments and a list object is set for the key.

Conclusion #

The Python "KeyError: 3" exception is caused when we try to access a 3 key in a dictionary that doesn't contain the key. To solve the error, set the key in the dictionary before trying to access it or conditionally set it if it doesn't exist.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.