要查找多层嵌套字典的值,可以使用递归方法。下面是一个示例代码:
def find_value(nested_dict, keys):
if len(keys) == 1:
return nested_dict.get(keys[0])
else:
key = keys[0]
if key in nested_dict:
return find_value(nested_dict[key], keys[1:])
else:
return None
# 示例字典
example_dict = {
'a': {
'b': {
'c': 123
}
}
}
# 查找值
keys = ['a', 'b', 'c']
value = find_value(example_dict, keys)
print(value) # 输出: 123
在这个示例中,find_value
函数接受两个参数:nested_dict
表示嵌套字典,keys
表示要查找的键的列表。函数首先判断keys
列表的长度,如果只有一个元素,则直接返回对应的值。如果keys
列表的长度大于1,则取第一个键作为当前层级的键,并在nested_dict
中查找该键对应的值。如果键存在,将递归调用find_value
函数来继续查找下一层级的值;如果键不存在,返回None
表示未找到。
使用示例字典example_dict
和要查找的键['a', 'b', 'c']
调用find_value
函数,将返回值123。