Python - Get particular Nested level Items from Dictionary

Dictionaries in Python allow you to store key-value pairs, making it easy to organize and access data efficiently. Sometimes, we may need to retrieve specific items from nested levels within a dictionary. We can use recursion, isinstance() with recursion, and dict.get() methods to extract nested-level items from dictionaries. In this article, we will explore different ways to get particular nested-level items from Dictionary in Python.

Nested Dictionary

A nested dictionary is a dictionary that contains other dictionaries as values. This allows for the creation of hierarchical structures, where data is organized in a tree-like fashion. Each level of the hierarchy represents a key-value pair, with the value being another dictionary. Accessing items from such a structure requires a specific approach to navigating through the levels of the tree.

Example Structure

company_data = {
    'employees': {
        'John': {
            'age': 30,
            'position': 'Manager',
            'department': 'Sales'
        },
        'Emily': {
            'age': 25,
            'position': 'Developer',
            'department': 'IT'
        }
    }
}

print(company_data['employees']['John']['position'])
Manager

Method 1: Using Recursion

By using the recursive method, we can easily retrieve items from nested levels within a dictionary without explicitly specifying each level. It provides a flexible and efficient solution, especially when dealing with complex data structures.

Algorithm

  • Define a function that takes the dictionary data and a list of keys representing the nested levels.

  • Check if the keys list is empty. If it is, return the data as it represents the value at the desired nested level.

  • Otherwise, get the first key from the keys list

  • Check if the key exists in the data dictionary. If it does, recursively call the function with the value corresponding to the key as the new data argument and the remaining keys.

  • If the key doesn't exist, return None or a default value to indicate that the item is not found.

Example

In the below example, we define the get_nested_item function, which takes the data dictionary and a list of keys as arguments ?

def get_nested_item(data, keys):
    if len(keys) == 0:
        return data

    key = keys[0]
    if key in data:
        return get_nested_item(data[key], keys[1:])
    else:
        return None

company_data = {
    'employees': {
        'John': {
            'age': 30,
            'position': 'Manager',
            'department': 'Sales'
        },
        'Emily': {
            'age': 25,
            'position': 'Developer',
            'department': 'IT'
        }
    }
}

keys = ['employees', 'John', 'position']
position = get_nested_item(company_data, keys)
print(position)

# Try with non-existent key
keys2 = ['employees', 'David', 'position']
position2 = get_nested_item(company_data, keys2)
print(position2)
Manager
None

Method 2: Using isinstance() with Recursion

The isinstance() function in Python is used to check the type of an object. It returns True if the object is an instance of the specified type, and False otherwise. We can use this function along with recursion to navigate through the levels of nested dictionaries dynamically.

Example

In the below example, we use isinstance(data, dict) to check if the data is a dictionary. If it is, we proceed with the recursive call. This check ensures that we navigate through valid dictionary levels and avoid encountering errors ?

def get_nested_item_safe(data, keys):
    if len(keys) == 0:
        return data

    key = keys[0]
    if isinstance(data, dict) and key in data:
        return get_nested_item_safe(data[key], keys[1:])
    else:
        return None

company_data = {
    'employees': {
        'John': {
            'age': 30,
            'position': 'Manager',
            'department': 'Sales'
        },
        'Emily': {
            'age': 25,
            'position': 'Developer',
            'department': 'IT'
        }
    }
}

keys = ['employees', 'John', 'position']
position = get_nested_item_safe(company_data, keys)
print(position)

# Try accessing from non-dict value
keys3 = ['employees', 'John', 'age', 'invalid']
result = get_nested_item_safe(company_data, keys3)
print(result)
Manager
None

Method 3: Using dict.get() Method

The dict.get() method is a useful way to retrieve a value from a dictionary and provide a default value if the key is not found. It is a more concise and safe approach compared to using direct dictionary indexing, especially when dealing with nested dictionaries.

Example

In the below example, we use company_data.get('employees', {}).get('John', {}).get('position', 'Unknown') to retrieve the position of employee 'John'. By using dict.get() at each level, we ensure that the code handles missing keys without raising an error ?

company_data = {
    'employees': {
        'John': {
            'age': 30,
            'position': 'Manager',
            'department': 'Sales'
        },
        'Emily': {
            'age': 25,
            'position': 'Developer',
            'department': 'IT'
        }
    }
}

# Get existing value
position = company_data.get('employees', {}).get('John', {}).get('position', 'Unknown')
print(f"John's position: {position}")

# Try with missing employee
position2 = company_data.get('employees', {}).get('David', {}).get('position', 'Unknown')
print(f"David's position: {position2}")

# Try with missing department
missing_dept = company_data.get('departments', {}).get('HR', {}).get('manager', 'Not found')
print(f"HR manager: {missing_dept}")
John's position: Manager
David's position: Unknown
HR manager: Not found

Comparison

Method Pros Cons Best For
Basic Recursion Simple, flexible Can raise errors Known structure
isinstance() + Recursion Type-safe, flexible More complex Dynamic structures
dict.get() Chain Concise, safe Gets verbose for deep nesting Simple access patterns

Conclusion

In this article, we explored three methods to get particular nested level items from dictionaries: recursion, isinstance() with recursion, and dict.get() chaining. Use dict.get() for simple cases, isinstance() with recursion for dynamic structures, and basic recursion when the dictionary structure is known and consistent.

Updated on: 2026-03-27T08:47:33+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements