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 the isinstance() with the recursion method and dict.get() method to get the nested−level items from the dictionary. 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 fo the tree.

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, let's call it get_nested_item, that takes two arguments: 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 get_nested_item function with the value corresponding to the key as the new data argument and the remaining keys in the keys list.

  • 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. We check if the keys list is empty; if it is, we return the data value. Otherwise, we retrieve the first key from the keys list and check if it exists in the data dictionary. If it does, we recursively call the get_nested_item function with the corresponding value as the new data and the remaining keys in the keys list. If the key is not found, we return None.

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

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

Output

Manager

Method 2: Using isinstance() along 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.

Algorithm

  • Define a function, let's call it get_nested_item, that takes two arguments: 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 data is a dictionary using isinstance(data, dict). If it is, recursively call the get_nested_item function with the value corresponding to the key as the new data argument and the remaining keys in the keys list.

  • If the data is not a dictionary or 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 use ,isinstance(data, dict) to check if the data is a dictionary. If it is, we proceed with the recursive call to get_nested_item. This check ensures that we navigate through valid dictionary levels and avoid encountering errors when accessing keys that do not exist.

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

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

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

Output

Manager

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 or when the existence of a key is not Known.

Example

In the below example, we have a nested dictionary company_data representing employee information. 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 easily handles missing keys without raising an error. In case any key is missing, the default value 'Unknown' is returned.

company_data = {
    'employees': {
        'John': {
            'age': 30,
            'position': 'Manager',
            'department': 'Sales'
        },
        'Emily': {
            'age': 25,
            'position': 'Developer',
            'department': 'IT'
        }
    }
}
position = company_data.get('employees', {}).get('John', {}).get('position', 'Unknown')
print(position)

Output

Manager

Conclusion

In this article, we discussed how we can get particular nested level items from the dictionary using recursion,isinstance, and recursion method and also using dict.get() method. The dict.get() method is particularly useful when you are uncertain about the presence of a key or when you want to handle missing keys easily. The isinstance() function and recursion enable us to navigate through nested dictionaries efficiently.

Updated on: 18-Jul-2023

794 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements