SoFunction
Updated on 2025-03-04

The causes and problems of Python KeyError exceptions

What is a KeyError exception?

In Python,KeyErrorExceptions are one of the built-in exceptions, specifically,KeyErroris an exception thrown when trying to get a key that does not exist in the dictionary. For reference, a dictionary is a data structure that stores data in key-value pairs, and the value in the dictionary is obtained through its key.

Python KeyError Common reasons and examples

Take the dictionary of the country and its capital as an example:

dictionary_capitals = {'BeiJing': 'China', 'Madrid': 'Spain', 'Lisboa': 'Portugal', 'London': 'United Kingdom'}

To search for information in a dictionary, you need to specify a key in parentheses, and Python will return the relevant value.

dictionary_capitals['BeiJing']

'China'

If you get a key that is not in the dictionary, Python will throw itKeyErrorException error message.

dictionary_capitals['Rome']

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Rome'

This exception will also be encountered when trying to get keys that do not exist in other Python dictionaries. For example, the system's environment variables.

# Get an environment variable that does not exist['USERS']
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  File "/Library/Frameworks//Versions/3.9/lib/python3.9/", line 679, in __getitem__
    raise KeyError(key) from None
KeyError: 'USERS'

Handle Python KeyError exception

There are two strategies to deal withKeyErrorException, first, avoidKeyError, the second is to captureKeyError

Prevent KeyError

Python throws if you try to get a non-existent keyKeyError. To prevent this, you can use.get()Get the key in the dictionary. If you encounter a non-existent key using this method, Python will returnNoneInstead ofKeyError

print(dictionary_capitals.get('Prague'))

None

Alternatively, you can check whether the key exists before getting it. This method of preventing exceptions is called "Look Before You Leap", or LBYL for short. In this case, you can useifStatement to check whether the key exists. If it does not exist, thenelseProcessed in clause.

capital = "Prague"
if capital in dictionary_capitals.keys():
    value = dictionary_capitals[capital]
else:
    print("The key {} is not present in the dictionary".format(capital)) 

Catch KeyError by exception handling

The second method is called "Easier to Ask Forgiveness Than Permission", or EAFP for short, and is a standard method for handling exceptions in Python.

Adopting the EAFP encoding style means assuming that there is a valid key and catching exceptions when an error occurs. The LBYL method depends on the if/else statement, and EAFP depends on the try/except statement.

The following example, instead of checking whether the key exists, try to get the required key. If for some reason the key does not exist, then just capture theKeyErrorProcessing.

capital = "Prague"
try:
     value = dictionary_capitals[capital]
except KeyError:
     print("The key {} is not present in the dictionary".format(capital))  

Python Advanced Processing KeyError

Use defaultdict

Python returns when obtaining keys that do not exist in the dictionaryKeyErrorException..get()The method is a fault-tolerant method, but not the optimal solution.

The Collections module provides a better way to deal with dictionaries. Unlike standard dictionary, defaultdict gets a non-existent key and throws a specified default value.

from collections import defaultdict 

# Defining the dict 
capitals = defaultdict(lambda: "The key doesn't exist") 
capitals['Madrid'] = 'Spain'
capitals['Lisboa'] = 'Portugal'
print(capitals['Madrid']) 
print(capitals['Lisboa']) 
print(capitals['Ankara']) 

 Spain
Portugal
The key doesn't exist

This is the article about the causes and problem solving of Python KeyError exceptions. For more related contents of Python KeyError exceptions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!