通过键列表访问嵌套字典项? [英] Access nested dictionary items via a list of keys?
问题描述
我有一个复杂的字典结构,我想通过一个键列表来访问正确的项目。
dataDict = {
a:{
r:1,
s:2,
t:3
$ bb:{
u:1,
v:{
x:1,
y 2,
z:3
},
w:3
}
}
maplist = [a ,r]
或
maplist = [b,v,y]
我已经制作了以下代码,但如果有人有想法,我肯定会有更好和更有效的方法。
#从字典获取给定的数据,位置提供为列表
def getFromDict(dataDict,mapList):
for map in mapList:dataDict = dataDict [k]
return dataDict
#在字典中设置一个给定的数据,位置提供为一个列表
def setInDict(dataDict,mapList,value):
for map in mapList [: - 1]:dataDict = dataDict [k]
dataDict [mapList [-1]] = value
使用 reduce()
遍历字典:
从functools导入减少#的前向兼容性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])
pre>
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' 'v':{'w':4,'x':1,'y':2,'z':3},'w':3}}
I have a complex dictionary structure which I would like to access via a list of keys to address the correct item.
dataDict = { "a":{ "r": 1, "s": 2, "t": 3 }, "b":{ "u": 1, "v": { "x": 1, "y": 2, "z": 3 }, "w": 3 } } maplist = ["a", "r"]
or
maplist = ["b", "v", "y"]
I have made the following code which works but I'm sure there is a better and more efficient way to do this if anyone has an idea.
# 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
解决方案Use
reduce()
to traverse the dictionary:from functools import reduce # forward compatibility for Python 3 import operator def getFromDict(dataDict, mapList): return reduce(operator.getitem, mapList, dataDict)
and reuse
getFromDict
to find the location to store the value forsetInDict()
:def setInDict(dataDict, mapList, value): getFromDict(dataDict, mapList[:-1])[mapList[-1]] = value
All but the last element in
mapList
is needed to find the 'parent' dictionary to add the value to, then use the last element to set the value to the right key.Demo:
>>> 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}}
这篇关于通过键列表访问嵌套字典项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!