Check if a nested key exists in a Dictionary in Python

avatar
Borislav Hadzhiev

Last updated: Feb 22, 2023
6 min

banner

# Table of Contents

  1. Check if a nested key exists in a Dictionary in Python
  2. Check if a nested key exists in a Dictionary using dict.get()
  3. Remove keys from a nested Dictionary in Python
  4. Remove keys from a nested Dictionary without mutating original

Note: If you need to remove keys from a nested dictionary, click on the following subheading:

# Check if a nested key exists in a Dictionary in Python

Use a try/except statement to check if a nested key exists in a dictionary.

If one or more of the nested keys doesn't exist, a KeyError is raised and is then handled by the except block.

main.py
my_dict = { 'address': { 'country': 'Finland', 'city': 'Oulu' } } try: city = my_dict['address']['city'] print(city) # ๐Ÿ‘‰๏ธ Oulu except KeyError: print('The specified key does NOT exist') # ------------------------------------------------- try: result = my_dict['not']['found']['key'] except KeyError: # ๐Ÿ‘‡๏ธ this runs print('The specified key does NOT exist')

check if nested key exists in dictionary

We try to access a nested key in the try block of the try/except statement.

# If one of the keys doesn't exist, a KeyError exception is raised

If one of the keys doesn't exist, a KeyError exception is raised and is then handled by the except block.

You can use a pass statement if you need to ignore the exception.

main.py
my_dict = { 'address': { 'country': 'Finland', 'city': 'Oulu' } } try: result = my_dict['not']['found']['key'] except KeyError: pass

using try except to handle the error

The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.

# Creating a reusable function

If you have to do this often, extract the logic into a reusable function.

main.py
def keys_exists(dictionary, keys): nested_dict = dictionary for key in keys: try: nested_dict = nested_dict[key] except KeyError: return False return True my_dict = { 'address': { 'country': 'Finland', 'city': 'Oulu' } } # ๐Ÿ‘‡๏ธ True print( keys_exists(my_dict, ['address', 'city']) ) # ๐Ÿ‘‡๏ธ False print( keys_exists(my_dict, ['key', 'not', 'found']) )

creating reusable function

The function takes a dictionary and a list of keys and checks if the sequence of keys exist in the dictionary.

We iterate over the list of keys and try to access each nested key, so the order of the keys in the list is important.

The function returns True if the sequence of keys exists in the dictionary, otherwise False is returned.

Alternatively, you can use the dict.get() method.

# Table of Contents

  1. Check if a nested key exists in a Dictionary using dict.get()
  2. Remove keys from a nested Dictionary in Python
  3. Remove keys from a nested Dictionary without mutating original

# Check if a nested key exists in a Dictionary using dict.get()

This is a three-step process:

  1. Use the dict.get() method to get each key.
  2. Specify an empty dictionary as a default value if the key doesn't exist.
  3. You can chain as many calls to the dict.get() method as necessary.
main.py
my_dict = { 'address': { 'country': 'Finland', 'city': 'Oulu' } } result = my_dict.get('address', {}).get('city') print(result) # ๐Ÿ‘‰๏ธ Oulu result = my_dict.get('key', {}).get('not', {}).get('found') print(result) # ๐Ÿ‘‰๏ธ None

check if nested key exists in dictionary using dict get

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.

We passed an empty dictionary as the second argument to the dict.get() method, so we can chain multiple calls to the method even if the nested key doesn't exist.

If the specified key doesn't exist an empty dictionary is returned on which we can safely call the dict.get() method again.

You don't have to pass an empty dictionary in the last call to dict.get() because the method returns None if a default value is not provided and the key doesn't exist.

main.py
my_dict = { 'address': { 'country': 'Finland', 'city': 'Oulu' } } result = my_dict.get('key', {}).get('not', {}).get('found') print(result) # ๐Ÿ‘‰๏ธ None

Which approach you pick is a matter of personal preference. I'd use a try/except statement because I find them quite direct and easy to read.

# Table of Contents

  1. Remove keys from a nested Dictionary in Python
  2. Remove keys from a nested Dictionary without mutating original

# Remove keys from a nested Dictionary in Python

To remove keys from a nested dictionary:

  1. Use a for loop to iterate over the collection of keys to remove.
  2. Remove all direct keys from the dictionary.
  3. Iterate over the dictionary's values and recursively remove the specified keys.
main.py
def remove_nested_keys(dictionary, keys_to_remove): for key in keys_to_remove: if key in dictionary: del dictionary[key] for value in dictionary.values(): if isinstance(value, dict): remove_nested_keys(value, keys_to_remove) return dictionary my_dict = { 'address': { 'country': 'Finland', 'city': 'Oulu', }, 'name': 'Frank', 'age': 30, } # ๐Ÿ‘‡๏ธ {'address': {'country': 'Finland'}, 'name': 'Frank'} print(remove_nested_keys(my_dict, ['city', 'age']))

remove keys from nested dictionary

This function mutates the original dictionary. If you'd rather create a new dictionary with the updated key-value pairs, scroll down to the next subheading.

We created a reusable function that takes a dictionary and a list of keys and removes the specified nested and non-nested keys from the dictionary.

The first step is to iterate over the list of keys to be removed.

main.py
for key in keys_to_remove: if key in dictionary: del dictionary[key]

On each iteration, we check if the key is present in the dictionary and if the condition is met, we remove the key.

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

This for loop takes care of removing all of the specified non-nested keys.

The next step is to iterate over the dictionary's values.

main.py
for value in dictionary.values(): if isinstance(value, dict): remove_nested_keys(value, keys_to_remove)

The dict.values method returns a new view of the dictionary's values.

main.py
my_dict = {'id': 1, 'name': 'bobbyhadz'} print(my_dict.values()) # ๐Ÿ‘‰๏ธ dict_values([1, 'bobbyhadz'])
On each iteration, we check if the current value is a dictionary and if the condition is met, we call the remove_nested_keys function with the nested dictionary and the list of keys to remove.

Then the function iterates over the list of keys again and uses the del to remove the specified keys.

The isinstance function returns True if the passed-in object is an instance or a subclass of the passed-in class.

main.py
# ๐Ÿ‘‡๏ธ True print( isinstance({'site': 'bobbyhadz.com'}, dict) ) # ๐Ÿ‘‡๏ธ False print( isinstance(['a', 'b', 'c'], dict) )

checking the type of a variable

The function removes the keys from the nested dictionary in place. In other words, it mutates the original dict object.

# Remove keys from a nested Dictionary without mutating original

If you'd rather not mutate the original dictionary:

  1. Use a for loop to iterate over the dictionary's items.
  2. Check if each key is not in the list of keys to be removed.
  3. If the current key is not a dictionary, add the key-value pair to a new dictionary.
  4. If the key is a dictionary, call the function recursively.
main.py
# โœ… function returns new dictionary (does NOT mutate original) def remove_nested_keys(dictionary, keys_to_remove): new_dict = {} for key, value in dictionary.items(): if key not in keys_to_remove: if isinstance(value, dict): new_dict[key] = remove_nested_keys(value, keys_to_remove) else: new_dict[key] = value return new_dict my_dict = { 'address': { 'country': 'Finland', 'city': 'Oulu', }, 'name': 'Frank', 'age': 30, } result = remove_nested_keys(my_dict, ['country', 'name']) print(result) # ๐Ÿ‘‰๏ธ {'address': {'city': 'Oulu'}, 'age': 30} result = remove_nested_keys(my_dict, ['city', 'age']) print(result) # ๐Ÿ‘‰๏ธ {'address': {'country': 'Finland'}, 'name': 'Frank'}

We used a for loop to iterate over the dictionary's items.

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

main.py
my_dict = {'id': 1, 'name': 'BobbyHadz'} # ๐Ÿ‘‡๏ธ dict_items([('id', 1), ('name', 'BobbyHadz')]) print(my_dict.items())

On each iteration, we check if the current key is not one of the keys to be removed.

main.py
for key, value in dictionary.items(): if key not in keys_to_remove: if isinstance(value, dict): new_dict[key] = remove_nested_keys(value, keys_to_remove) else: new_dict[key] = value

The isinstance() function then checks if the key points to a dictionary value.

If the key stores a dictionary, the remove_nested_keys function is invoked with the nested dictionary and the list of keys to remove.

If the key doesn't store a dictionary, the key-value pair gets added to the new dictionary.

The function returns the newly constructed dictionary excluding all of the keys in the list.

# 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