Jorge Nachtigall
Jorge Nachtigall

Reputation: 539

List inside a list - how to access an element

This is my code:

def liveGame(summonerName):
req = requests.get('https://br1.api.riotgames.com/lol/spectator/v3/active-games/by-summoner/' + str(summonerName) + '?api_key=' + apikey)
req_args = json.loads(req.text)
print(req_args)

And this is what I'm receiving from my request.get:

{
    'gameId': 1149933395,
    'mapId': 11,
    'participants': [
        {
            'teamId': 100,
            'spell1Id': 11,
            'spell2Id': 4,
            'championId': 141,
            'profileIconId': 7,
            'summonerName': 'Disneyland Party',
            ...
        }
    ]
}

I've simplified the return of the request, but as you can see the 'participants' index is another list. So, how can I access the contents of this list (teamId, Spell1Id, etc)?

I can only access the full list this way:

print(req_args['participants'])

But, what I want to do is access only one element of the 'participants' list.

I'm using Python 3.6.

Upvotes: 0

Views: 462

Answers (2)

Surinder Batti
Surinder Batti

Reputation: 109

this is simple to get value from dictionary object.

print items['participants'][0].get('teamId')

print items['participants'][0].get('spell1Id')

Upvotes: 0

viveksyngh
viveksyngh

Reputation: 787

You can access this list items using index as you do for normal list If you want to access first element for req_args['participants'] you can use

req_args['participants'][i]

where i is nothing but the index of item that you want to access from list.

Since items inside linked list are dictionaries to access teamId and spellId of only one item ( in this case first item) you can do following

req_args['participants'][0]['teamId']
req_args['participants'][0]['spell1Id']

you can also iterate over list to access each dictionary and value of teamId, spell1Id or others keys present inside dictionary like this

for participant in req_args['participants']:
    print(participant['teamId'])
    print(participant['spell1Id'])

Upvotes: 1

Related Questions