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

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

Barbara Streisand
Barbara StreisandOriginal
2024-12-18 16:47:14277browse

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

Accessing Nested Dictionary Items with a Key List

When dealing with complex dictionary structures, traversing them to access specific items can be a common challenge. Finding an efficient and flexible approach to navigate these dictionaries is crucial.

Consider the scenario where you have a nested dictionary like:

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

You may need to access these items using a list of keys, such as ["a", "r"] or ["b", "v", "y"]. While the approach below may work:

# Get a given data from a dictionary with position provided as a list
def getFromDict(dataDict, mapList):
    for k in mapList:
        dataDict = dataDict[k]
    return dataDict

There exists a more efficient method using Python's reduce():

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

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

This improved method utilizes reduce to traverse the dictionary, using the operators.getitem function to access each nested item using the key list.

For setting values, we can leverage getFromDict to locate the correct 'parent' dictionary and then assign the value:

def setInDict(dataDict, mapList, value):
    getFromDict(dataDict, mapList[:-1])[mapList[-1]] = value

This method efficiently traverses the dictionary to the appropriate location in the data structure and updates the value.

Finally, we can provide snake_case function names and extend these functions to work with mixed data types, resulting in:

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

def get_by_path(root, items):
    return reduce(operator.getitem, items, root)

def set_by_path(root, items, value):
    get_by_path(root, items[:-1])[items[-1]] = value

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

These functions provide a versatile utility for navigating and manipulating nested dictionaries, lists, or a mix of the two.

The above is the detailed content of How to 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