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

Python遍历字典组成的列表报TypeError: list indices must be integers错误如何解决

错误原因

你的问题出在列表遍历的逻辑上:
当使用for i in cars遍历列表时,迭代得到的i直接就是cars列表中的每一个字典元素,而非列表的下标索引。此时你再用cars[i]的方式取值,相当于把字典作为列表的索引传入,自然触发了列表索引必须是整数或切片,不能是字典的类型报错。

修复方案

方案1:直接使用迭代的字典元素(常规推荐写法)

不需要再通过列表取元素,直接用迭代得到的i即可:

cars = [
    {
        "name": "Ford",
        "type": "SHORT",
        "coded": {
            "1": "Escape",
            "2": "Fiesta",
            "999": "Gumbo"
        }
    },
    {
        "name": "Honda",
        "type": "SHORT",
        "coded": {
            "1": "Civic",
            "2": "CRV",
            "VCR": "Accord"
        }
    }
]

for i in cars:
    for x, y in i["coded"].items():
        print(x, y)

方案2:通过下标索引遍历(适用于需要用到索引的场景)

如果需要通过下标取值,要先迭代列表的索引范围:

for i in range(len(cars)):
    for x, y in cars[i]["coded"].items():
        print(x, y)

两种方案运行后都能得到预期输出:

1 Escape
2 Fiesta
999 Gumbo
1 Civic
2 CRV
VCR Accord

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 23:18:01