Home > Blockchain >  How can I loop through the dictionary and sets to get to my desired values?
How can I loop through the dictionary and sets to get to my desired values?

Time:05-04

I have the following code with a nested dictionary and I want to access the "assists" value for each participant and append it. How do I do that?

gameData = {
"metadata": {
    "dataVersion": "2",
    "matchId": "NA1_4263873346",
    "participants": [
        "Sw_wTB5fzxXvyXeCovgcGhKNw4hLKzgcEvWFKzMqZWtfiJ7HtbxYOK6Nb7nBU5SR-B3bNt4Ay9bvjQ",
        "-t2_OfuyZFaCdZJ1lvbbfRFgYS1FWZcGhIsqj-8m-SS9UZ9wFyYeWBiGkcMgNEl_geH5CF9tX4SAzQ",
        "A-n0X4QWr8Jr0PISogZK3VpnIqqVbm87jchMYpTrUrhiSfeoxVCl8ImnJxaE_lg9pIAdxNgaFpkT7g"
    ]
},
"info": {
    "gameVersion": "12.6.431.7988",
    "mapId": 11,
    "participants": [
        {
            "assists": 9,
            "deaths": 5,
            "kills": 1
        },
        {
            "assists": 1,
            "deaths": 3,
            "kills": 1
        },
        {
            "assists": 3,
            "deaths": 5,
            "kills": 6
        } 
    ]
}

I use this to loop through them but it returns the error "TypeError: list indices must be integers or slices, not str".

participants = []
for row in gameData['metadata']['participants']:
    participants_row = {}
    participants_row['assists'] = gameData['info']['participants']['assists']
    participants.append(participants_row)

Can anyone help me understand how to loop through it to get the desired values?

CodePudding user response:

You have several mistakes in accessing parts of the dict.

I think you meant this:

# d = {"metadata": { ...
participants = []
for p in d['info']['participants']:
    participants_row = {}
    participants_row['assists'] = p['assists']
    participants.append(participants_row)
print(participants)

CodePudding user response:

    participants_row['assists'] = match_detail['info']['participants']['assists']

I assume this line of code causes the error. To debug this, break it down into smaller pieces:

info = match_detail['info']
participants = info['participants']
assists = participants['assists']

If you do this, you will see that the third line causes the error. So add

print(participants)

Now we see that participants is a list, but you are using it like a dictionary.

I think you want the assists from each participant. One way to do this is with a list comprehension:

assists = [p['assists'] for p in participants]
  • Related