nested_dict = {
'outer_key1': {
'middle_key1': {
'inner_key1': 'value1',
'inner_key2': 'value2'
},
'middle_key2': {
'inner_key1': 'value3'
}
},
'outer_key2': {
'middle_key1': {
'inner_key1': 'value4'
}
}
}
获取inner_key1
在outer_key1
和middle_key1
下的值:
value = nested_dict['outer_key1']['middle_key1']['inner_key1']
print(value) # 输出: value1
使用递归函数,遍历嵌套结构以找到所有的最内层键值对:
def find_inner_key_values(d, inner_key='inner_key1', current_keys=()):
for k, v in d.items():
new_keys = current_keys + (k,)
if isinstance(v, dict):
# 递归调用find_inner_key_values
yield from find_inner_key_values(v, inner_key, new_keys)
elif k == inner_key:
# 当找到最内层的键时,返回键和它的完整路径
yield new_keys, v
# 获取所有inner_key1的值
for keys, value in find_inner_key_values(nested_dict, 'inner_key1'):
print(keys, value)
'''
输出:
(('outer_key1', 'middle_key1', 'inner_key1'), 'value1')
(('outer_key1', 'middle_key2', 'inner_key1'), 'value3')
(('outer_key2', 'middle_key1', 'inner_key1'), 'value4')
'''