正确引用嵌套字典和列表|蟒蛇

时间:2020-04-29 08:40:49

标签: python json list dictionary

这样做

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”不是“固定装置”列表中的第一项吗?

如何正确引用'team_id'?

谢谢!

1 个答案:

答案 0 :(得分:1)

您将要引用字典并错误地列出。要获取团队ID,请参考下面的字典:

h2 = {'api': {'fixtures': [{'awayTeam': {'logo': 'https://media.api-sports.io/football/teams/157.png','team_id': 157,'team_name': 'Bayern Munich'},'elapsed': 90}]}}

team_id1 = 157 # just to test if condition
for fixture in h2['api']['fixtures']:
    if fixture['awayTeam']['team_id'] == team_id1:
        print (fixture['awayTeam']['team_id'])
        # (do something with fixture['awayTeam']['team_id'])