Home >Backend Development >Python Tutorial >How Can I Efficiently Access and Update Nested Dictionary Items in Python Using a List of Keys?

How Can I Efficiently Access and Update Nested Dictionary Items in Python Using a List of Keys?

DDD
DDDOriginal
2024-12-27 02:53:08450browse

How Can I Efficiently Access and Update Nested Dictionary Items in Python Using a List of Keys?

Accessing Nested Dictionary Items Using a List of Keys

Accessing nested dictionary structures can be a common task in Python programming. Here, we explore a more efficient approach than the provided code for retrieving and modifying data within a complex dictionary using a list of keys.

Using reduce() for Enhanced Traversal

The reduce() function is a powerful tool for transforming a sequence of values by applying a single operation. In this case, we can use it to traverse the dictionary structure, reducing the list of keys into a single value. The operator.getitem method is used as the operation to retrieve the next dictionary level at each iteration.

from functools import reduce  # forward compatibility for Python 3
import operator

def get_from_dict(data_dict, map_list):
    return reduce(operator.getitem, map_list, data_dict)

Updating Data with reduce() and operator.setitem

To update nested dictionary values, we can reuse get_from_dict to retrieve the parent dictionary and use the operator.setitem method to set the value.

def set_in_dict(data_dict, map_list, value):
    get_from_dict(data_dict, map_list[:-1])[map_list[-1]] = value

Example Usage

Let's test our code:

data_dict = {
    "a": {
        "r": 1,
        "s": 2,
        "t": 3
        },
    "b": {
        "u": 1,
        "v": {
            "x": 1,
            "y": 2,
            "z": 3
            },
        "w": 3
        }
    }    

map_list = ["a", "r"]
print(get_from_dict(data_dict, map_list))  # Output: 1

map_list = ["b", "v", "y"]
print(get_from_dict(data_dict, map_list))  # Output: 2

map_list = ["b", "v", "w"]
set_in_dict(data_dict, map_list, 4)
print(data_dict)  # Updated dictionary with "w": 4

This enhanced approach leverages powerful Python functions like reduce() and operator.getitem to efficiently perform nested dictionary operations, making your code cleaner and more efficient.

The above is the detailed content of How Can I Efficiently Access and Update Nested Dictionary Items in Python Using a List of Keys?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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