Python - “映射”字典的键列表

时间:2014-03-05 21:48:04

标签: python list dictionary syntax

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

示例:

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

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

# and I want to print out the value of `three` ("Final word")

2 个答案:

答案 0 :(得分:7)

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

submain = main
for key in mylist:
    submain = submain[key]
print submain

答案 1 :(得分:3)

相当于mhlester的解决方案,具有函数式编程的味道:

import operator
print reduce(operator.getitem, mylist, main)