我有一个python中的多维字典,还有一个列表,其中有我想要访问的键。从字典中获取价值的最简单方法是什么?
例子:
main = {
'one': {
'two': {
'three': "Final word"
}
}
}
mylist = ['one', 'two', 'three']
# and I want to print out the value of `three` ("Final word")
最佳答案
循环mylist
,存储中间dict(我称之为submain
),直到您用完mylist
元素:
submain = main
for key in mylist:
submain = submain[key]
print submain