How to Ignore a KeyError exception in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

Ignore a KeyError exception in Python #

Use a try/except block to ignore a KeyError exception in Python. The except block is only going to run if a KeyError exception was raised in the try block. You can use the pass keyword to ignore the exception.

main.py
my_dict = {'name': 'Alice'} try: print(my_dict['age']) except KeyError: # 👇️ this runs pass # 👇️ you can use continue instead of pass # if you are in a for loop and want to skip to next iteration for i in range(3): try: print(my_dict['age']) except KeyError: # 👇️ this runs continue

If you just want to ignore the KeyError exception if it is thrown, use a try/except block.

The age key is not present in the dictionary, so a KeyError is raised and our except block runs.

You can use the pass keyword if you don't want to handle the error in any way.

If you are in a for loop and want to skip to the next iteration, use the continue keyword instead.

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

main.py
my_dict = {'name': 'Alice'} print(my_dict.get('age')) # 👉️ None print(my_dict.get('age', '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.

Another common way to avoid the KeyError exception is to use the in operator and check if the key is present in the dictionary before accessing it.

main.py
my_dict = {'name': 'Alice'} if 'age' in my_dict: print(my_dict['age']) else: # 👇️ this runs print('key is not present in the dict')

The in operator tests for membership. For example, x in s evaluates to True if x is a member of s, otherwise it evaluates to False.

x not in s returns the negation of x in s.

All built-in sequences and set types support the in and not in operators.

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

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.