gpt4 book ai didi

python - 通过键列表访问嵌套字典项?

转载 作者:太空宇宙 更新时间:2023-11-03 20:54:51 26 4
gpt4 key购买 nike

我有一个复杂的字典结构,我想通过键列表访问它以找到正确的项目。

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()遍历字典:

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

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

并重用getFromDict来查找存储setInDict()值的位置:

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

除了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 风格指南 prescribes snake_case names for functions 。上面的方法同样适用于列表或字典和列表的混合,因此名称实际上应该是 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]]

关于python - 通过键列表访问嵌套字典项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56086147/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com