autosnake
autosnake

Reputation: 23

Correctly referencing nested dictionaries and lists | Python

By doing

response=requests.get(url,headers=headers)
    h2h=json.loads(response.text)

I receive the dictionary h2h which looks like this:

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

I am now trying to do something with all fixtures of a certain team like this:

for i in h2h['api']['fixtures']: #for each fixture
        if ['awayTeam']['team_id']==team_id1:
           #do something...

Then I receive an error:

if ['awayTeam']['team_id']==(team_id1):
TypeError: list indices must be integers or slices, not str

For ['awayTeam'][0] I receive no error, which would mean that 'awayTeam' is a list.

Why is 'awayTeam' a list and not a dictionary? Isn't 'awayTeam' the first item in the 'fixtures' list?

How do I correctly reference 'team_id'?

Thanks a bunch!

Upvotes: 1

Views: 65

Answers (1)

Hayden Eastwood
Hayden Eastwood

Reputation: 966

You are going about referencing your dictionary and lists incorrectly. To get team ID, reference the dictionary as I have done below:

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'])

Upvotes: 1

Related Questions