【发布时间】:2020-04-29 08:40:49
【问题描述】:
通过做
response=requests.get(url,headers=headers)
h2h=json.loads(response.text)
我收到的字典 h2h 如下所示:
{'api': {'fixtures': [{'awayTeam': {'logo': 'https://media.api-sports.io/football/teams/157.png',
'team_id': 157,
'team_name': 'Bayern Munich'},
'elapsed': 90,
我现在正在尝试对某个团队的所有固定装置做一些这样的事情:
for i in h2h['api']['fixtures']: #for each fixture
if ['awayTeam']['team_id']==team_id1:
#do something...
然后我收到一个错误:
if ['awayTeam']['team_id']==(team_id1):
TypeError: list indices must be integers or slices, not str
对于 ['awayTeam'][0] 我没有收到任何错误,这意味着 'awayTeam' 是一个列表。
为什么“awayTeam”是一个列表而不是字典? 'awayTeam' 不是 'fixtures' 列表中的第一项吗?
如何正确引用“team_id”?
非常感谢!
【问题讨论】:
-
嗨!有时当只有一个项目时,结果不是一个列表,而是另一个包含你想要的数据的字典,我建议之前检查数据类型并相应地为这两种情况添加逻辑。
标签: python json list dictionary