温馨提示×

python之怎么查找多层嵌套字典的值

小亿
93
2024-01-30 10:28:00
栏目: 编程语言

要查找多层嵌套字典的值,可以使用递归方法。下面是一个示例代码:

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。

0