我在Python中有一个多维字典,我有一个列表,其中包含我想要访问的密钥。从字典中获取价值的最简单方法是什么?
示例:
main = {
'one': {
'two': {
'three': "Final word"
}
}
}
mylist = ['one', 'two', 'three']
# and I want to print out the value of `three` ("Final word")
答案 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)