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

Python TypeError问题:遍历JSON字典时出现string indices must be integers错误

问题解决:遍历JSON字典时出现TypeError错误

原始代码

@app.route("/", subdomain="dev")
def devhome():
    with open("D:/moviewebsite/movielist.json", "r") as f:
        movielist = json.load(f)
    goodmovies = []
    for item in movielist:
        if str(item["link"])[-4:] == ".mp4":
            goodmovies.append(item)
    else:
        return render_template("devHome.html", movielist=goodmovies)

参考JSON片段

{
    "12 Years a Slave.mp4": {
        "title": "12 Years a Slave",
        "link": "12 Years a Slave.mp4",
        "count": 1,
        "download": "https://linknotimportant/12 Years a Slave.mp4",
        "torrent": ""
    }
}

错误信息

File "d:\moviewebsite\app.py", line 70, in devhome
    if str(item["link"])[-4:] == ".mp4":
TypeError: string indices must be integers

错误原因

从JSON加载的movielist是一个字典,直接用for item in movielist遍历,得到的item是字典的键名(比如示例中的"12 Years a Slave.mp4"字符串),而非对应的电影对象字典。此时尝试用item["link"],相当于对字符串使用字符串索引,自然触发TypeError。

解决方案

修改遍历方式,直接遍历字典的值(即每个电影对象):

@app.route("/", subdomain="dev")
def devhome():
    with open("D:/moviewebsite/movielist.json", "r") as f:
        movielist = json.load(f)
    goodmovies = []
    # 遍历字典的所有值,item即为每个电影的字典对象
    for item in movielist.values():
        # 用endswith更简洁,无需转字符串再切片
        if item["link"].endswith(".mp4"):
            goodmovies.append(item)
    # 移除多余的for-else结构,直接返回结果
    return render_template("devHome.html", movielist=goodmovies)

额外优化

  • 使用str.endswith(".mp4")替代切片判断,代码更简洁且可读性更高
  • 移除原代码中多余的for-else结构,因为for循环结束后直接返回结果即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:01:31