Solve - KeyError exception when assigning new Key in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Andrew Svk

Solve - KeyError exception when assigning new Key in Python #

A KeyError exception is raised when assigning a new key in a dictionary when trying to assign a nested key. To solve the error, conditionally set the key or use the defaultdict class to set a default value for keys that don't exist in the dictionary.

keyerror when assigning new key

Here is an example of how the error occurs.

main.py
employee = { 'name': 'Alice' } # ⛔️ KeyError: 'address' employee['address']['country'] = 'Austria'

We tried to assign a nested key in the dictionary, however the address key doesn't exist, so we got a KeyError.

One way to solve the error is to assign a value for the address key first.

main.py
employee = { 'name': 'Alice' } employee['address'] = {} # 👈️ assign key to empty dict employee['address']['country'] = 'Austria' # 👇️ {'name': 'Alice', 'address': {'country': 'Austria'}} print(employee)

We set the address key to an empty dictionary, so we were able to assign the nested country key.

However, this would override the address key if it were already set in the dictionary.

You can only assign the key if it isn't already present in the dictionary.

main.py
employee = { 'name': 'Alice' } if 'address' not in employee: employee['address'] = {} employee['address']['country'] = 'Austria' # 👇️ {'name': 'Alice', 'address': {'country': 'Austria'}} print(employee)

The if statement is only ran if the address key is not in the dictionary.

You can also use the defaultdict class to set default values for keys that don't already exist in the dictionary.

main.py
from collections import defaultdict employee = defaultdict(dict) employee['address']['country'] = 'Austria' # 👇️ defaultdict(<class 'dict'>, {'address': {'country': 'Austria'}}) print(employee) print(employee['address']) # 👉️ {'country': 'Austria'}

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 dict class to the constructor, so every time we try to access a key that doesn't exist, the dict class is called without any arguments and a dict object is set for the key.

Here is a simple example of how defaultdict objects work.

main.py
from collections import defaultdict my_dict = defaultdict(int) print(my_dict['a']) # 👉️ 0

The a key is not present in the dict, so the int() class gets invoked without any arguments and a 0 value gets set for the key we tried to access.

You can also use a try/except statement to handle a KeyError exception while adding a new key to a dictionary.

main.py
employee = { 'name': 'Alice' } try: employee['address']['country'] = 'Austria' except KeyError: employee['address'] = {} employee['address']['country'] = 'Austria' # 👇️ {'name': 'Alice', 'address': {'country': 'Austria'}} print(employee)

The KeyError exception gets handled by the except clause where we assign the address key and set a value for the nested country key.

Use the search field on my Home Page to filter through my more than 1,000 articles.