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

Python运行报TypeError: 'type' object is not subscriptable如何解决

错误原因

触发TypeError: 'type' object is not subscriptable的核心原因是版本兼容问题:

  • Python 3.9才正式支持直接用内置类型list[str]/dict[str, int]这种写法做泛型类型注解,3.8及更早版本里list/dict是普通类型对象,不支持下标索引写法,直接写就会抛出该类型错误。
  • 额外注意:代码里标注错误位置用的//不是Python合法单行注释(Python单行注释用#),同时字典就地合并运算符|=也是Python 3.9新增语法,低版本运行也会报错。
解决方法

方案1:兼容Python 3.8及更早版本(无需升级Python)

  1. 从typing模块导入低版本支持的泛型类型List、Dict替换内置的list、dict做类型注解
  2. 把非法的//注释替换为#注释或者直接删除
  3. 把3.9才支持的|=字典合并写法替换为通用的update()方法

修改后可直接运行的完整代码:

from collections import Counter
from typing import List, Dict
import json  # Only for pretty printing `data` dictionary.


def get_keyword_counts(text: str, keywords: List[str]) -> Dict[str, int]:
    return {
        word: count for word, count in Counter(text.split()).items()
        if word in set(keywords)
    }
# 原错误触发位置:低版本不支持list[str]/dict[str, int]类型注解写法

def main() -> None:
    data = {
        "policy": {
            "1": {
                "ID": "ML_0",
                "URL": "www.a.com",
                "Text": "my name is Martin and here is my code"
            },
            "2": {
                "ID": "ML_1",
                "URL": "www.b.com",
                "Text": "my name is Mikal and here is my code"
            }
        }
    }
    keywords = ['is', 'my']
    for policy in data['policy'].values():
        policy.update(get_keyword_counts(policy['Text'], keywords))
    print(json.dumps(data, indent=4))


if __name__ == '__main__':
    main()

方案2:升级Python到3.9及以上版本

如果可以升级运行环境,只需要删除代码里非法的//注释行,原代码的类型注解和|=运算符都可以正常运行,不需要修改其他逻辑。

运行效果

代码正常执行后会输出统计完成的结构化数据,每个文本条目下会追加对应关键词的出现次数:

{
    "policy": {
        "1": {
            "ID": "ML_0",
            "URL": "www.a.com",
            "Text": "my name is Martin and here is my code",
            "my": 2,
            "is": 2
        },
        "2": {
            "ID": "ML_1",
            "URL": "www.b.com",
            "Text": "my name is Mikal and here is my code",
            "my": 2,
            "is": 2
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 15:00:49