我有一个复杂的字典结构,我想通过键列表访问它以解决正确的项目。
dataDict = { "a":{ "r": 1, "s": 2, "t": 3 }, "b":{ "u": 1, "v": { "x": 1, "y": 2, "z": 3 }, "w": 3 } } maplist = ["a", "r"]
或者
maplist = ["b", "v", "y"]
我已经制作了以下有效的代码,但我确信如果有人有想法,有更好、更有效的方法来做到这一点。
# 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 # Set a given data in a dictionary with position provided as a list def setInDict(dataDict, mapList, value): for k in mapList[:-1]: dataDict = dataDict[k] dataDict[mapList[-1]] = value
用于reduce()遍历字典:
reduce()
from functools import reduce # forward compatibility for Python 3 import operator def getFromDict(dataDict, mapList): return reduce(operator.getitem, mapList, dataDict)
并重getFromDict用以找到存储值的位置setInDict():
getFromDict
setInDict()
def setInDict(dataDict, mapList, value): getFromDict(dataDict, mapList[:-1])[mapList[-1]] = value
除了最后一个元素之外的所有元素mapList都需要找到“父”字典来添加值,然后使用最后一个元素将值设置为正确的键。
mapList
演示:
>>> getFromDict(dataDict, ["a", "r"]) 1 >>> getFromDict(dataDict, ["b", "v", "y"]) 2 >>> setInDict(dataDict, ["b", "v", "w"], 4) >>> import pprint >>> pprint.pprint(dataDict) {'a': {'r': 1, 's': 2, 't': 3}, 'b': {'u': 1, 'v': {'w': 4, 'x': 1, 'y': 2, 'z': 3}, 'w': 3}}
请注意,Python PEP8 样式指南规定了函数的蛇案例名称。以上对于列表或字典和列表的混合同样适用,因此名称应该是get_by_path()and set_by_path():
get_by_path()
set_by_path()
from functools import reduce # forward compatibility for Python 3 import operator def get_by_path(root, items): """Access a nested object in root by item sequence.""" return reduce(operator.getitem, items, root) 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
为了完成,删除键的功能:
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]]