VOOZH about

URL: https://www.geeksforgeeks.org/python/check-if-a-nested-key-exists-in-a-dictionary-in-python/

⇱ Check If a Nested Key Exists in a Dictionary in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check If a Nested Key Exists in a Dictionary in Python

Last Updated : 23 Jul, 2025

Dictionaries are a versatile and commonly used data structure in Python, allowing developers to store and retrieve data using key-value pairs. Often, dictionaries may have nested structures, where a key points to another dictionary or a list, creating a hierarchical relationship. In such cases, it becomes essential to check if a nested key exists before attempting to access it to avoid potential errors.

Here, we'll explore some simple and generally used examples to demonstrate how to check if a nested key exists in a dictionary in Python.

Check If A Nested Key Exists In A Dictionary In Python

Below, are the method of checking if A Nested Key Exists In A Dictionary In Python.

Basic Nested Key

In this example, This code checks if the key 'inner' exists within the nested dictionary under the key 'outer' in `my_dict`, then prints its value if found, otherwise, prints a message indicating its absence.


Output
Nested Key 'inner' exists with value: value

Check If A Nested Key Exists In A Dictionary Using get() Method

In this example, the code safely accesses the nested key 'inner' within the dictionary under the key 'outer' in `my_dict` using the `get()` method, avoiding potential KeyError. It then prints the value if the key exists, or a message indicating its absence if not.


Output
Nested Key 'inner' exists with value: value

Check If A Nested Key Exists In A Dictionary Using try and except

In this example, the code uses a try-except block to attempt accessing the nested key 'inner' within the dictionary under the key 'outer' in `my_dict`. If the key exists, it prints the corresponding value; otherwise, it catches the KeyError and prints a message indicating the absence of the nested key.


Output
Nested Key 'inner' exists with value: value

Check If A Nested Key Exists In A Dictionary Using Recursive Function

In this example, This recursive function, `nested_key_exists`, checks if a series of nested keys, given as a list ('outer' -> 'inner'), exists within the dictionary `my_dict`. It prints a message indicating the existence or absence of the specified nested key.


Output
Nested Key 'inner' exists.
Comment