Last updated: Apr 8, 2024
Reading timeยท8 min
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.
Here is an example of how the error occurs.
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.
One way to avoid the exception is to use the dict.get()
method.
my_dict = {1: ['c', 'd'], 2: ['e', 'f']} print(my_dict.get(0)) # ๐๏ธ None print(my_dict.get(0, '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:
Name | Description |
---|---|
key | The key for which to return the value |
default | The 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.
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, '')) # ๐๏ธ ""
Another way to solve the error is to set a value for the specific key before trying to access it.
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']
We initialized the 0
key to an empty list in the example.
Now we can safely access the key without getting a KeyError
exception.
You can also check if the key doesn't exist in the dictionary before setting it.
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']
We check if the 0
key doesn't exist in the dictionary and initialize its value
to an empty list.
try/except
statement to handle the errorYou can also use a try/except statement to handle the error.
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
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.
dict.items()
method to iterate over a dictionaryUse the dict.items()
method if you need to iterate over a dictionary.
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']
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.
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
.
# [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.
defaultdict
class to solve the errorYou can also use the defaultdict
class to avoid the error.
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.
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.
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.
One way to solve the error is to assign a value for the address
key first.
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.
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.
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.
defaultdict
class to set a default value for keys that don't existYou can also use the defaultdict
class to set default values for keys that
don't already exist in the dictionary.
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.
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.
try/except
statement when setting the keyYou can also use a try/except
statement to handle a KeyError
exception while
adding a new key to a dictionary.
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.
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.
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.
dict
object.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.
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.
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.
If you only need to access a specific key and need to ignore the KeyError
exception, use the dict.get()
method.
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:
Name | Description |
---|---|
key | The key for which to return the value |
default | The 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 you aren't trying to access the key incorrectly.
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.
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.
You can learn more about the related topics by checking out the following tutorials: