You need to enable JavaScript to run this app. Python如何递归遍历嵌套字典列表并返回匹配结果,解决返回None问题
优惠活动
大模型
产品
解决方案
定价
更多

Python如何递归遍历嵌套字典列表并返回匹配结果,解决返回None问题

Python嵌套结构递归查找返回None的解决方案

问题原因

  • 递归调用未传递返回值:子层级找到匹配项后返回的结果,没有被上层接收并继续向上传递,函数执行完所有遍历后没有匹配的返回分支,默认返回None
  • 缺少节点类型判断:未判断节点是否为字典就执行"name" in node操作,遇到字符串、列表等非字典类型时会触发运行错误
  • 直接返回递归调用的逻辑错误:如果在循环里不加判断直接return recurse(...),第一个子元素遍历未匹配就会直接终止全部遍历,不会检查后续元素

修复方案

每次递归调用后检查返回值,如果返回非None说明已找到目标,直接向上传递返回值即可终止全部遍历,不需要再检查后续元素。

修复后代码

def recurse(node, finding, round=0):
    print(str(round) + " -> " + str(node))
    # 先判断是字典再检查name字段,避免非字典类型报错
    if isinstance(node, dict) and "name" in node:
        if node["name"] == finding:
            print("FOUND!!!")
            return node
    # 遍历列表元素
    if isinstance(node, list):
        for item in node:
            res = recurse(item, finding, round+1)
            # 子层级找到结果,直接向上返回,终止后续遍历
            if res is not None:
                return res
    # 遍历字典值
    if isinstance(node, dict):
        for key, value in node.items():
            res = recurse(value, finding, round+1)
            # 子层级找到结果,直接向上返回,终止后续遍历
            if res is not None:
                return res
    # 所有分支都未匹配,显式返回None
    return None


def main():
    fruit = [
        {
            "green": [
                    {"name": "apple"},
                    {"price": "good"},
                    "random string"
                ],
            "red":  [
                    {"name": "strawberry"},
                    "another random string",
                    {"price": "high"}
                ]
        },
        "final random string",
        {
            "yellow": [
                    {"name": "peach"},
                    {"price": "bad at winter"}
                ]
        }
    ]
    print(recurse(fruit, "strawberry"))

main()

运行效果

运行后会在匹配到strawberry后立刻终止所有遍历,最终输出预期结果:

...前面遍历输出省略
3 -> {'name': 'strawberry'}
FOUND!!!
{'name': 'strawberry'}

内容的提问来源于stack exchange,提问作者Erdős András

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 05:36:08