KeyError: 0 exception in Python [Solved]

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
8 min

banner

# Table of Contents

  1. KeyError: 0 exception in Python
  2. KeyError exception when assigning new Key in Python
  3. (JSON) KeyError exception in Python

# KeyError: 0 exception in Python

The Python "KeyError: 0" exception is caused when we try to access a 0 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 use dict.get() to get a default value if the key doesn't exist.

keyerror 0

Here is an example of how the error occurs.

main.py
my_dict = {1: ['c', 'd'], 2: ['e', 'f']} # โ›”๏ธ KeyError: 0 print(my_dict[0])

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

# Using the dict.get() method

One way to avoid the exception is to use the dict.get() method.

main.py
my_dict = {1: ['c', 'd'], 2: ['e', 'f']} print(my_dict.get(0)) # ๐Ÿ‘‰๏ธ None print(my_dict.get(0, 'default value')) # ๐Ÿ‘‰๏ธ default value

using dict get to solve the error

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 use any default value that suits your use case, e.g. None, 0 or an empty string.

main.py
my_dict = {1: ['c', 'd'], 2: ['e', 'f']} print(my_dict.get(0, None)) # ๐Ÿ‘‰๏ธ None print(my_dict.get(0, 0)) # ๐Ÿ‘‰๏ธ 0 print(my_dict.get(0, '')) # ๐Ÿ‘‰๏ธ ""

using default values that suit your use case

# Set a value for the key before accessing it

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

main.py
my_dict = {1: ['c', 'd'], 2: ['e', 'f']} my_dict[0] = [] # ๐Ÿ‘ˆ๏ธ initialize key to empty list my_dict[0].append('a') my_dict[0].append('b') print(my_dict[0]) # ๐Ÿ‘‰๏ธ ['a', 'b']

set value for key before accessing it

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

Now we can safely access the key without getting a KeyError exception.

# Checking if the key doesn't exist before setting it

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

main.py
my_dict = {1: ['c', 'd'], 2: ['e', 'f']} # โœ… initialize key if it doesn't exist if 0 not in my_dict: my_dict[0] = [] my_dict[0].append('a') my_dict[0].append('b') print(my_dict[0]) # ๐Ÿ‘‰๏ธ ['a', 'b']

check if key does not exist before setting it

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

# Using a try/except statement to handle the error

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

main.py
my_dict = {1: ['c', 'd'], 2: ['e', 'f']} try: print(my_dict[0]) except KeyError: # ๐Ÿ‘‡๏ธ this runs print('key does not exist in dict') my_dict[0] = [] # ๐Ÿ‘ˆ๏ธ can initialize key if necessary

using try except statement to handle the error

Trying to access the 0 key in the dictionary causes a KeyError exception which then gets passed to the except block.

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

# Use the dict.items() method to iterate over a dictionary

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

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

using dict items method to iterate over dictionary

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

You can also use the range() class when iterating over a dictionary.

main.py
my_dict = {1: ['b'], 3: ['c'], 5: ['d']} for index in range(0, 10): if index in my_dict: # ['b'] # ['c'] # ['d'] print(my_dict[index])

The for loop uses the range class to get an iterator from 0 to 9.

main.py
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(list(range(0, 10)))

On each iteration, we check if the index is present in the dictionary before accessing it.

# Using the defaultdict class to solve the error

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

main.py
from collections import defaultdict my_dict = defaultdict(list) my_dict[0].append('a') my_dict[0].append('b') print(my_dict) # ๐Ÿ‘‰๏ธ defaultdict(<class 'list'>, {0: ['a', 'b']})

Notice that you have to import the defaultdict class before using it.

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.

# 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.

Here is an example of how the error occurs.

main.py
employee = { 'name': 'Bobby Hadz' } # โ›”๏ธ 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 exception.

# Assigning a value for the key first

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.

# Checking if the key exists before assigning a value

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 run if the address key is not in the dictionary.

# Using the defaultdict class to set a default value for keys that don't exist

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.

# Using a try/except statement when setting the key

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.

# (JSON) KeyError exception in Python

To solve the (JSON) KeyError exception in Python, use the json.loads() method to parse the JSON string into a native Python object and conditionally check if the key is present in the dictionary before accessing it.

main.py
import json my_json = r'{"name": "Alice", "age": 30}' # ๐Ÿ‘‡๏ธ Parse JSON string to Python dict my_dict = json.loads(my_json) print(my_dict) # ๐Ÿ‘‰๏ธ {'name': 'Alice', 'age': 30} # ๐Ÿ‘‡๏ธ Check if the key is present in the dictionary if 'country' in my_dict: print(my_dict['country'])

The json.loads() method parses a JSON string into a native Python object.

We used the in operator to check if the country key is present in the dictionary before accessing it.

When used with a dictionary, the operators check for the existence of the specified key in the dict object.

# Setting the key to a default value if it isn't present

Alternatively, you can check if the key is not in the dictionary and set it to a default value, e.g. an empty string or an empty list.

main.py
import json my_json = r'{"name": "Alice", "age": 30}' my_dict = json.loads(my_json) print(my_dict) # ๐Ÿ‘‰๏ธ {'name': 'Alice', 'age': 30} if 'country' not in my_dict: my_dict['country'] = '' print(my_dict['country']) # ๐Ÿ‘‰๏ธ ''

We only set the country key to an empty string if it isn't already present in the dictionary.

When debugging, use the dict.keys() method to print the dictionary's keys.

main.py
import json my_json = r'{"name": "Alice", "age": 30}' my_dict = json.loads(my_json) print(my_dict) # ๐Ÿ‘‰๏ธ {'name': 'Alice', 'age': 30} # ๐Ÿ‘‡๏ธ ['name', 'age'] print(list(my_dict.keys()))

If you try to access any other key, you'll get the KeyError exception.

# Ignoring the KeyError exception

If you only need to access a specific key and need to ignore the KeyError exception, use the dict.get() method.

main.py
import json my_json = r'{"name": "Alice", "age": 30}' my_dict = json.loads(my_json) print(my_dict) # ๐Ÿ‘‰๏ธ {'name': 'Alice', 'age': 30} print(my_dict.get('country')) # ๐Ÿ‘‰๏ธ None print(my_dict.get('country', '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 arguments:

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.

# Make sure to access the key correctly

Make sure you aren't trying to access the key incorrectly.

main.py
import json my_json = r'{"address": {"country": "Austria"}}' my_dict = json.loads(my_json) print(my_dict) # ๐Ÿ‘‰๏ธ {'address': {'country': 'Austria'}} print(my_dict['address']['country']) # ๐Ÿ‘‰๏ธ 'Austria'

Notice that we first have to access the address key before accessing the nested country key.

If you have an array, make sure to access it at a specific index before trying to access a key.

main.py
import json my_json = r'[{"address": {"country": "Austria"}}]' my_list = json.loads(my_json) print(my_list) # ๐Ÿ‘‰๏ธ [{'address': {'country': 'Austria'}}] print(my_list[0]['address']['country']) # ๐Ÿ‘‰๏ธ 'Austria'

We parsed the JSON string into a list. Notice that we first have to access the list at index 0 to get a dict object.

Once we have a dict object, we can access its specific keys.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev