Back to Blog Page
Programming

How to Fix Python KeyError

How to Fix Python KeyError

Written by Kolade Chris | Dec 21, 2024 | #Error #Python | 2 minutes Read

A KeyError occurs in Python when you try to access a key in a dictionary that doesn’t exist. Sometimes, the key exists but the error is still raised.

If you’re getting this error and are looking for a fix, you’ve come to the right place, because I’ll show you the causes of the error and fix for each of those causes.

So, let’s talk about the causes of the error first.

What Causes KeyError in Python

The causes of the error include but not limited to:

  • leading or trailing spaces attached to keys
  • there’s a typo in the key
  • wrong access of the data type of the key
  • key exists in nested dictionaries
  • subtle errors with non-printable characters like \n and \t

How to Fix KeyError in Python

Let’s examine the fix for each cause of the KeyError mentioned above.

  • If you have trailing spaces or a typo, the error will be raised:
1
my_dict = {'name': 'John', 'age': 24}
2
3
print(my_dict['Name']) # KeyError: 'Name'
4
print(my_dict[' name ']) # KeyError: ' name '

Remove that trailing space and fix the typo and everythin will be fine:

1
my_dict = {'name': 'John', 'age': 24}
2
3
print(my_dict['name']) # John
4
print(my_dict['name']) # John
  • If you mix up the data of a key, due to some confusion or something else, Python will throw the KeyError:
1
my_dict = {4: 'four', 1: 'one', 5: 'five', 2: 'two'}
2
print(my_dict['1']) # KeyError: '1'

In the case above, the key 1 is an integer, not a string.

To fix it, you either access the key as it’s exact integer data type or cast it to an integer with the int() function if you want to wrap quotes around it for consistency in key assessment:

1
my_dict = {4: 'four', 1: 'one', 5: 'five', 2: 'two'}
2
3
4
print(my_dict[int('1')]) # one
5
print(my_dict[1]) # one
  • If you’re dealing with nested keys and values, but you try to access a key on the surface, Python will throw the KeyError at you:
1
my_nested_dict = {
2
'outer': {
3
'name': 'John',
4
'age': 30
5
}
6
}
7
8
print(my_nested_dict['name']) # KeyError: 'name'

To access the key correctly, you have to have nested standard assess too:

1
my_nested_dict = {
2
'outer': {
3
'name': 'John',
4
'age': 30
5
}
6
}
7
8
print(my_nested_dict['outer']['name']) # John

If it happens you have more deeply nested keys and values, you can use the get method:

1
my_nested_dict = {
2
'outer': {
3
'name': 'John',
4
'age': 30,
5
'address': {
6
'city': 'New York',
7
'zipcode': '10001'
8
},
9
'hobbies': ['reading', 'travelling']
10
}
11
}
12
13
name = my_nested_dict.get('outer', {}).get('name', 'Name not found')
14
zipcode = my_nested_dict.get('outer', {}).get('address', {}).get('zipcode', 'Zipcode not found')
15
16
print(name) # John
17
print(zipcode) # 10001
  • To fix or prevent the KeyError while workign with external data that might have non-printable characters like \n and \t, you can use the get() method along with the strip() method to assess the key:
1
print(data.get(key.strip(), 'Key not found'))

How to Fix the KeyError while Working with JSON

If you’re working with a JSON data and the KeyError occurs, the fixes already discussed apply too, since you normally have to load JSON data into a dictionary to work with it.

1
import json
2
3
4
json_data = '''
5
{
6
"company": {
7
"employees": [
8
{
9
"name": "Alice",
10
"position": "Developer"
11
},
12
{
13
"name": "Bob",
14
"position": "Manager",
15
"details": {
16
"age": 40,
17
"city": "New York"
18
}
19
}
20
]
21
}
22
}
23
'''
24
25
# Load the JSON data into a Python dictionary
26
company_data = json.loads(json_data)
27
28
# Safely access deeply nested data using get()
29
bob_city = company_data.get('company', {}).get('employees', [])[1].get('details', {}).get('city', 'City not found')
30
bob_age = company_data.get('company', {}).get('employees', [])[1].get('details', {}).get('age', 'City not found')
31
alice_age = company_data.get('company', {}).get('employees', [])[0].get('details', {}).get('age', 'Age not found')
32
33
print(bob_city) # New York
34
print(bob_age) # 40
35
print(alice_age) # Age not found (since details doesn't exist for Alice)