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

How Can I Efficiently Access and Modify Nested Dictionary Items Using a Key List in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-12-16 02:33:10965browse

How Can I Efficiently Access and Modify Nested Dictionary Items Using a Key List in Python?

Accessing Nested Dictionary Items via a Key List: Exploring a Nested Structure

Complex data structures like dictionaries often require efficient methods to traverse and manipulate their nested content. One common challenge is accessing specific items within a nested structure based on a provided list of keys.

Existing Approach

One method to address this is to iteratively navigate through the dictionary, using each key in the list to locate the desired item. This approach, however, can become increasingly verbose and error-prone for deeply nested structures.

Improved Solution Using Reduce

A more elegant and efficient solution involves leveraging Python's reduce() function. reduce() iteratively applies a specified operation to a sequence of elements, reducing the sequence to a single value. By utilizing operator.getitem as the operation, we can traverse the dictionary, using each key in the list to retrieve the associated value.

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

def get_from_dict(dataDict, mapList):
    return reduce(operator.getitem, mapList, dataDict)

Setting a Value

The same principle can be applied to modify values within the dictionary. By using get_from_dict to locate the parent dictionary and the final key, we can directly assign the new value.

def set_in_dict(dataDict, mapList, value):
    get_from_dict(dataDict, mapList[:-1])[mapList[-1]] = value

Additional Functions

Expanding on the core functionality, we can create additional functions for deleting and manipulating nested structures. For example, a function to delete a key:

def del_by_path(root, items):
    del get_from_path(root, items[:-1])[items[-1]]

Complete Example

Here's a complete demonstration of the code:

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

maplist = ["a", "r"]
print(get_from_dict(dataDict, maplist))  # Output: 1

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

set_in_dict(dataDict, ["b", "v", "w"], 4)

print(dataDict)  # Output: {'a': {'r': 1, 's': 2, 't': 3}, 'b': {'u': 1, 'v': {'w': 4, 'x': 1, 'y': 2, 'z': 3}, 'w': 3}}

This improved approach offers a concise and efficient method to navigate and modify complex nested dictionary structures using a list of keys, providing flexibility and code readability.

The above is the detailed content of How Can I Efficiently Access and Modify Nested Dictionary Items Using a Key List in Python?. 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