Home > Backend Development > Python Tutorial > Python - Get specific nesting level items from dictionary

Python - Get specific nesting level items from dictionary

PHPz
Release: 2023-08-20 14:37:13
forward
838 people have browsed it

Python - 从字典中获取特定的嵌套级别项

In Python, dictionaries allow you to store key-value pairs, making it easy to organize and access data efficiently. Sometimes, we may need to retrieve a specific item from a nested level of the dictionary. We can get nested level items from the dictionary using isinstance() with the recursive method and the dict.get() method. In this article, we will explore different ways of getting items from a Python dictionary at a specific nesting level.

Nested Dictionary

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

Method 1: Use 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, which accepts two parameters: dictionary data and a list of keys representing the nested level.

  • Check if the key list is empty. If empty, returns the data as it represents the value for the desired nesting level.

  • Otherwise, get the first key from the key list

  • Check whether the key exists in the data dictionary. If present, the get_nested_item function is called recursively using the value corresponding to that key as the new data parameter and the remaining keys in the key list.

  • If the key does not exist, return None or a default value to indicate that the item was not found.

The Chinese translation of

Example

is:

Example

In the example below, we define the get_nested_item function that accepts a data dictionary and a list of keys as parameters. We check if the key list is empty; if so, return the data value. Otherwise, we get the first key from the key list and check if it exists in the data dictionary. If it exists, we recursively call the get_nested_item function with the corresponding value as the new data and the remaining keys in the key list. If the key is not found, None is returned.

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)
Copy after login

Output

Manager
Copy after login
Copy after login
Copy after login

Method 2: Using isinstance() and recursion

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

algorithm

  • Define a function, let's call it get_nested_item, which accepts two parameters: dictionary data and a list of keys representing the nested level.

  • Check if the key list is empty. If empty, returns the data as it represents the value for the desired nesting level.

  • Otherwise, get the first key from the key list.

  • Use isinstance(data, dict) to check whether the data is a dictionary. If so, call the get_nested_item function recursively with the value of the corresponding key as a new data parameter and the remaining list of keys as parameters.

  • If the data is not a dictionary or the key does not exist, return None or a default value to indicate that the item is not found.

The Chinese translation of

Example

is:

Example

In the example below, we use isinstance(data, dict) to check if the data is a dictionary. If so, we continue calling get_nested_item recursively. This check ensures that we avoid errors accessing non-existent keys when navigating the valid dictionary hierarchy.

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)
Copy after login

Output

Manager
Copy after login
Copy after login
Copy after login

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 cleaner and safer approach than using a dictionary index directly, especially when dealing with nested dictionaries or when you don't know whether the key exists.

The Chinese translation of

Example

is:

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)
Copy after login

Output

Manager
Copy after login
Copy after login
Copy after login

in conclusion

In this article, we discussed how to get a specific nested level item from a dictionary using recursion, isinstance and recursive methods and using dict.get() method. The dict.get() method is particularly useful when you are unsure about the presence of a key or want to easily handle missing keys. The isinstance() function and recursion allow us to traverse nested dictionaries efficiently.

The above is the detailed content of Python - Get specific nesting level items from dictionary. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template