問題:
我們如何有效地存取和操作資料使用清單的深度嵌套字典結構鍵?
解:
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中文網其他相關文章!