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

如何使用Python遍历JSON数据提取deadline_time并解决列表索引报错

报错原因
  • 从提供的JSON结构可知,data['events']是列表类型,列表内的每一项才是包含deadline_time字段的字典对象
  • 原代码直接用字符串'deadline_time'作为列表的索引,不符合Python列表的取值规则,因此触发类型错误
修复代码

你需要先遍历data['events']列表中的所有字典元素,再从单个元素中提取deadline_time字段,修改后可运行的代码如下:

import json
from urllib.request import urlopen

with urlopen("https://fantasy.premierleague.com/api/bootstrap-static/") as response:
    source = response.read()

data = json.loads(source)

for event in data['events']:
    # 可选:用get方法避免字段不存在时报错,无对应字段时返回默认提示
    print(event.get('deadline_time', '未查询到deadline_time字段'))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 03:09:02