問題:
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