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

遍历列表字典触发TypeError:两段代码差异原因解析

问题分析与解决

报错代码及信息

你的代码:

listf = [
    {"name":"akram"}
]
for i in listf:
    print(listf["name"])

报错信息:

line 5, in <module>
    print(listf["name"])
TypeError: list indices must be integers or slices, not str

对比的正常执行代码

可正常运行的代码:

students = [
    {"name": "Hermione", "house": "Gryffindor", "patronus": "Otter"},
    {"name": "Harry", "house": "Gryffindor", "patronus": "Stag"},
    {"name": "Ron", "house": "Gryffindor", "patronus": "Jack Russell terrier"},
    {"name": "Draco", "house": "Slytherin", "patronus": None},
]

for student in students:
    print(student["name"], student["house"], student["patronus"], sep=", ")

输出结果:

Hermione, Gryffindor, Otter
Harry, Gryffindor, Stag
Ron, Gryffindor, Jack Russell terrier
Draco, Slytherin, None

差异原因

核心差异是循环体内访问的对象错误:

  • 正常代码中,for student in students 循环时,student 代表列表中每一个字典元素,用student["name"]是访问字典的键,符合语法规则。
  • 你的代码里,for i in listf 循环时,错误地尝试用字符串索引访问列表listf——列表只能使用整数索引(如listf[0])或切片,不能用字符串当索引,因此触发TypeError。你定义的循环变量i本应代表列表中的字典元素,但你并未使用它。

解决方法

将循环内的listf["name"]改为i["name"],修改后的代码如下:

listf = [
    {"name":"akram"}
]
for i in listf:
    print(i["name"])

运行后会正常输出akram。

内容的提问来源于stack exchange,提问作者TUSK ACT 4

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:40:31