我想使用列表中的项目作为字典键来查找嵌套字典中的值。
例如,给出以下列表:
keys = ['first', 'second', 'third']
我想这样做:
result = dictionary[keys[0]][keys[1]][keys[2]]
这相当于:
result = dictionary['first']['second']['third']
但我不知道预先在keys
列表中有多少项目(除了它总是至少有1个)。
答案 0 :(得分:1)
迭代地进入子区域。
result = dictionary
for key in keys:
result = result[key]
print(result)
答案 1 :(得分:0)
一个简单的for循环可以工作:
result = dictionary[keys[0]] # Access the first level (which is always there)
for k in keys[1:]: # Step down through any remaining levels
result = result[k]
演示:
>>> dictionary = {'first': {'second': {'third': 123}}}
>>> keys = ['first', 'second', 'third']
>>> result = dictionary[keys[0]]
>>> for k in keys[1:]:
... result = result[k]
...
>>> result
123
>>>