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

Python递归处理字典遇TypeError:'dict'对象不可调用求助

递归处理字典报错:TypeError: 'dict' object is not callable

问题场景

想用递归函数遍历字典并打印"Goal",运行代码时触发错误。

变量定义

asdf =  {'aws_iam_policy': {'vpc_flow_log_cloudwatch': {'__end_line__': 94,
                                                 '__start_line__': 88,
                                                 'count': ['${local.create_flow_log_cloudwatch_iam_role '
                                                           '? 1 : 0}'],
                                                 'name_prefix': ['vpc-flow-log-to-cloudwatch-'],
                                                 'policy': ['${data.aws_iam_policy_document.vpc_flow_log_cloudwatch[0].json}'],
                                                 'tags': ['${merge(var.tags,var.vpc_flow_log_tags)}']}}}

出错代码

def test(test:dict):
    for key, values in test.items():
        if type(values) is dict:
            test(values)                        # 报错:TypeError: 'dict' object is not callable
        else :
            print("Goal")
test(asdf)

错误输出

Traceback (most recent call last):
  File "/InitCloud/scan/scan/cand0.py", line 49, in <module>
    test(asdf)                          
  File "/InitCloud/scan/scan/cand0.py", line 45, in test
    test(values)                        # Error TypeError: 'dict' object is not callable
TypeError: 'dict' object is not callable

问题原因与修复

函数名和参数名都是test,在函数内部递归调用时,test已经被覆盖成传入的字典参数,自然会报错“字典对象不可调用”。

只需要把参数名改成和函数名不同的名称即可,同时推荐用isinstance替代type判断类型(兼容字典子类):

def test(d: dict):
    for key, values in d.items():
        if isinstance(values, dict):
            test(values)
        else:
            print("Goal")
test(asdf)

内容的提问来源于stack exchange,提问作者건양대배경석 7655

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:50:39