You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何检查嵌套字典及列表内的指定key是否存在并提取值

多层嵌套字典(含列表嵌套)指定key提取实现

功能1:遍历所有嵌套结构提取目标key

实现思路

  • 递归遍历所有结构:遇到字典则检查key是否在待查询列表中,匹配成功则存入结果
  • 遇到列表则遍历每个元素,继续向下递归搜索
  • 若同一个key在多个位置存在,默认保留第一个匹配到的值,可根据需求调整为保留所有值

完整代码

def extract_keys(nested_obj, target_keys, result=None):
    if result is None:
        result = {}
    # 处理字典类型
    if isinstance(nested_obj, dict):
        for k, v in nested_obj.items():
            if k in target_keys and k not in result:
                result[k] = v
            # 继续递归搜索下层
            extract_keys(v, target_keys, result)
    # 处理列表类型
    elif isinstance(nested_obj, list):
        for item in nested_obj:
            extract_keys(item, target_keys, result)
    return result

# 测试用例
dictABC = {
    "name": "bob",
    "id": "abs",
    "meta": {
        "v": "2",
        "update": "00"
    },
    "other": {
        "age": [
            {
                "a": "test",
                "b": "test1",
                "c": "test2"
            },
            {
                "a": "user",
                "b": "user1",
                "c": "user2"
            }
        ]
    }
}
list_keys = ["name", "update", "a"]
new_dict = extract_keys(dictABC, list_keys)
print(new_dict)

运行结果

{'name': 'bob', 'update': '00', 'a': 'test'}

如果需要保留同一个key的所有匹配值,只需要把result的value改成列表,匹配到就append即可。


功能2:检查指定嵌套路径是否存在

实现思路

把嵌套路径转换成列表(字典key用字符串,列表索引用整数),逐层校验每一层是否存在,避免直接索引抛出KeyError/IndexError

完整代码

def check_nested_path(nested_obj, path):
    current = nested_obj
    for p in path:
        # 检查字典场景
        if isinstance(current, dict):
            if p not in current:
                return False, None
            current = current[p]
        # 检查列表场景
        elif isinstance(current, list):
            if not isinstance(p, int) or p < 0 or p >= len(current):
                return False, None
            current = current[p]
        # 其他类型无法继续向下索引
        else:
            return False, None
    return True, current

# 测试路径:dictABC["other"]["age"][0]["a"]
path = ["other", "age", 0, "a"]
exists, value = check_nested_path(dictABC, path)
if exists:
    print(f"路径存在,对应值为:{value}")
else:
    print("路径不存在")

运行结果

路径存在,对应值为:test

内容的提问来源于stack exchange,提问作者uk_butterfly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 19:06:03