Python如何正确访问API返回的嵌套列表字典中的position字段?
解决API返回数据中position元素的访问问题
你的代码出现KeyError或AttributeError的原因有两个:
- API返回的
response字段是嵌套数组(外层数组里还有一个内层数组),你当前的response['response'][0]获取到的是内层数组,而非包含position的对象。 - 你试图访问的
id键在目标对象中不存在,实际需要获取的是position键。
正确的访问方式
首先确认API返回的结构(关键片段):
{ "get": "standings", "parameters": {"league": "12", "season": "2019-2020"}, "errors": [], "results": 1, "response": [ [ { "position": 1, "stage": "NBA - Regular Season", "group": {"name": "Western Conference", "points": null} } ] ] }
要获取position值,需要多一层数组索引:
# 假设API响应已解析为字典,存储在response变量中 position = response['response'][0][0]['position'] print(position) # 输出结果:1
额外排查建议
- 若仍报错,先打印
response['response']的内容,确认结构是否与预期一致:print(response['response']) - 检查键名拼写(JSON键区分大小写),确保没有写错
position。 - 查看
response['errors']是否为空数组,确认API请求无错误。
内容的提问来源于stack exchange,提问作者Cian Sullivan
相关产品推荐
相关产品推荐

