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

Python运行代码报TypeError: 'dict' object is not callable错误求助

错误原因

抛出TypeError: 'dict' object is not callable是因为字典取值语法错误:

  • Python字典取值必须使用方括号[]包裹键名,格式为dict[key]
  • 代码中误将方括号写为圆括号(),写成了mydict('name')的形式。圆括号的作用是调用可执行对象(函数、类等),字典本身不可被调用,解释器尝试执行调用逻辑时就会触发该报错。
修复方案

将字符串格式化行中所有字典取值的圆括号替换为方括号即可,修正后代码:

mydict = {"name":"Peter", "age":29, "hasaandroid":True}
mydict["location"] = "NewZealand"
print(mydict)

sentence = 'Hello my name is {} and i am {} years old. I live in {}.'.format(mydict['name'], mydict['age'], mydict['location'])
print(sentence)

运行输出:

{'name': 'Peter', 'age': 29, 'hasaandroid': True, 'location': 'NewZealand'}
Hello my name is Peter and i am 29 years old. I live in NewZealand.

简化写法参考

如果格式化占位符和字典键名一一对应,可以用字典解包的写法减少重复代码:

sentence = 'Hello my name is {name} and i am {age} years old. I live in {location}.'.format(**mydict)

该写法会自动将字典中的键值对匹配到同名占位符,运行效果和逐值传参完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 22:30:54