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

如何在多层嵌套字典中通过子串匹配查找含drop的键对应的值

解决方法

你可以用递归深度优先遍历(DFS)的方式扫描所有嵌套字典的键,不需要提前知道结构,只要键名包含drop子串就自动收集对应值,代码示例如下:

def find_key_by_substring(nested_dict, substring):
    result = []
    for key, value in nested_dict.items():
        # 匹配当前层级键
        if substring in key:
            result.append(value)
        # 值为字典时递归遍历下一层
        if isinstance(value, dict):
            result.extend(find_key_by_substring(value, substring))
        # 如果存在列表嵌套字典的场景,取消注释下面代码即可兼容
        # elif isinstance(value, list):
        #     for item in value:
        #         if isinstance(item, dict):
        #             result.extend(find_key_by_substring(item, substring))
    return result

# 注意:你提供的示例数据存在语法错误,字典键值对需用冒号而非等号,修正后如下
myList = {
    1: {'name': 'John', 'age': '27', 'class': '2', 'drop': True},
    2: {'name': 'Marie', 'other_info': {'age': '22', 'class': '3', 'dropped': True }},
    3: {'name': 'James', 'other_info': {'age': '23', 'class': '1', 'is_dropped': False}},
    4: {'name': 'Lucy', 'some_info': {'age': '20', 'class': '4', 'other_branch': {'is_dropped': True, 'how_drop': 'Foo'}}}
}

# 搜索所有包含drop的键对应的值
drop_values = find_key_by_substring(myList, 'drop')
print(drop_values)

运行后输出结果为[True, True, False, True, 'Foo'],你需要的四个目标值都在结果中,额外匹配的how_drop对应值可以手动筛选剔除。

扩展说明
  • 无需提前知晓字典嵌套层级,Python默认递归深度为1000,完全满足你说的20层以上嵌套需求
  • 要提取其他规则的内容时,仅需要修改调用函数的第二个参数即可,比如要提取所有带age的键的值,直接传'age'即可
  • 如果需要记录匹配键的完整路径方便筛选,可以使用带路径记录的版本:
def find_key_with_path(nested_dict, substring, path=""):
    result = []
    for key, value in nested_dict.items():
        current_path = f"{path}['{key}']" if path else f"'{key}'"
        if substring in key:
            result.append((key, current_path, value))
        if isinstance(value, dict):
            result.extend(find_key_with_path(value, substring, current_path))
    return result

返回结果会附带每个匹配项的完整层级路径,比如('is_dropped', "'4'['some_info']['other_branch']['is_dropped']", True),更方便你快速定位和筛选不需要的匹配项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:15:03