问题:
我们如何有效地访问和操作数据使用列表的深度嵌套字典结构键?
解决方案:
Python 原生函数 functools.reduce 可用于一次高效地遍历字典pass.
实现:
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)
用法:
要检索指定路径处的值,请使用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
设置值:
要在特定路径设置值,我们可以重用 get_by_path 来定位父字典并将值分配给想要的键:
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
用法:
maplist = ["b", "v", "w"] set_by_path(dataDict, maplist, 4)
附加功能:
为了完整性,我们还可以定义删除嵌套键值对的函数字典:
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]]
以上是如何使用键列表高效访问和修改嵌套 Python 字典中的数据?的详细内容。更多信息请关注PHP中文网其他相关文章!