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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:50:53