我有一个复杂的字典结构,我想通过一个键列表来访问它以找到正确的项目。dataDict = { \'a\':{ \'r\': 1, \'s\': ...
我有一个复杂的字典结构,我想通过一个键列表来访问它以找到正确的项目。
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
用递归解决了这个问题:
def get(d,l):
if len(l)==1: return d[l[0]]
return get(d[l[0]],l[1:])
使用你的例子:
dataDict = {
"a":{
"r": 1,
"s": 2,
"t": 3
},
"b":{
"u": 1,
"v": {
"x": 1,
"y": 2,
"z": 3
},
"w": 3
}
}
maplist1 = ["a", "r"]
maplist2 = ["b", "v", "y"]
print(get(dataDict, maplist1)) # 1
print(get(dataDict, maplist2)) # 2