Python访问新冠追踪API复杂字典元素触发TypeError问题求助
解决TypeError: list indices must be integers or slices, not str问题
错误原因
local_case_tracker['data']['regional']返回的是列表类型,里面的每个元素才是包含loc字段的字典。你试图用字符串'loc : Goa'作为列表的索引,而列表只接受整数或切片作为索引,因此触发TypeError。
解决方案
你需要遍历regional列表,找到loc字段值为Goa的字典元素:
方法1:普通循环遍历
# 初始化变量存储果阿邦数据 goa_data = None # 遍历地区列表 for region in local_case_tracker['data']['regional']: if region['loc'] == 'Goa': goa_data = region break # 找到后立即退出循环,提升效率 # 输出结果 if goa_data: print("果阿邦新冠数据:", goa_data) else: print("未查询到果阿邦的数据")
方法2:使用生成器表达式(更简洁)
# 找到第一个loc为Goa的条目,若不存在则返回None goa_data = next((item for item in local_case_tracker['data']['regional'] if item['loc'] == 'Goa'), None) if goa_data: print(goa_data)
补充说明
可以先执行print(type(local_case_tracker['data']['regional']))确认类型,输出会是<class 'list'>,这能直观解释为什么之前的索引方式不成立。
内容的提问来源于stack exchange,提问作者ArnavK
相关产品推荐
相关产品推荐

