Problem:
How can we efficiently access and manipulate data within a deeply nested dictionary structure using a list of keys?
Solution:
The native Python function functools.reduce can be utilized to traverse the dictionary efficiently in a single pass.
Implementation:
from functools import reduce import operator def get_by_path(root, items): """Access a nested object in root by item sequence.""" return reduce(operator.getitem, items, root)
Usage:
To retrieve the value at the specified path, use get_by_path:
dataDict = { "a": { "r": 1, "s": 2, "t": 3 }, "b": { "u": 1, "v": { "x": 1, "y": 2, "z": 3 }, "w": 3 } } maplist = ["a", "r"] value = get_by_path(dataDict, maplist) # 1
Setting Values:
To set a value at a particular path, we can reuse get_by_path to locate the parent dictionary and assign the value to the desired key:
def set_by_path(root, items, value): """Set a value in a nested object in root by item sequence.""" get_by_path(root, items[:-1])[items[-1]] = value
Usage:
maplist = ["b", "v", "w"] set_by_path(dataDict, maplist, 4)
Additional Functionality:
For completeness, we can also define a function to delete a key-value pair within the nested dictionary:
def del_by_path(root, items): """Delete a key-value in a nested object in root by item sequence.""" del get_by_path(root, items[:-1])[items[-1]]
The above is the detailed content of How Can I Efficiently Access and Modify Data in Nested Python Dictionaries Using a List of Keys?. For more information, please follow other related articles on the PHP Chinese website!