Python - "映射"字典的键列表

jst*_*knt 3 python syntax dictionary list

我在Python中有一个多维字典,我有一个列表,其中包含我想要访问的密钥.从字典中获取价值的最简单方法是什么?

例:

main = {
    'one': {
        'two': {
            'three': "Final word"
        }
    }
}

mylist = ['one', 'two', 'three']

# and I want to print out the value of `three` ("Final word")
Run Code Online (Sandbox Code Playgroud)

mhl*_*ter 7

循环mylist,存储一个中间字典(我称之为submain),直到你用完mylist元素:

submain = main
for key in mylist:
    submain = submain[key]
print submain
Run Code Online (Sandbox Code Playgroud)