遍历列表字典触发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
相关产品推荐
相关产品推荐

