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

   2024-11-08 4240
核心提示:要查找多层嵌套字典的值,可以使用递归方法。下面是一个示例代码:def find_value(nested_dict, keys):if len(keys) == 1:return

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

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。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号