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)
- 从
typing模块导入低版本支持的泛型类型List、Dict替换内置的list、dict做类型注解 - 把非法的
//注释替换为#注释或者直接删除 - 把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
相关产品推荐
相关产品推荐

