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
相关产品推荐
相关产品推荐

