问题:
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
解决方案:
参考一: https://en.stackoom.com/question/zeEs参考二: https://stackoom.com/question/zeEs