Search code examples
pythonjsonpython-3.xriot-games-api

Multiple python nested for loops, possibly recursively traverse lists. python 3


I am trying to match the first item in participantId to the first list in str(each['participantId']). And then the second item in participantId to second list, and so on.

participantId = ['2','5','7','4','10','9','2']

each['participantId'] = [[1,2,3,4,5,6,7,8,9,10],
                         [1,2,3,4,5,6,7,8,9,10],
                         [1,2,3,4,5,6,7,8,9,10],
                         [1,2,3,4,5,6,7,8,9,10],
                         [1,2,3,4,5,6,7,8,9,10],
                         [1,2,3,4,5,6,7,8,9,10],
                         [1,2,3,4,5,6,7,8,9,10]]

So I want to use a for loop on participantId but have just the first item in the list do an if statement with the first list, then the second item in participantId do an if statement with the second list. As of Now my code just matches all participantId's with each list. here is a snippet of my code:

for each in json['participants']:
                for x in str(each['participantId']):
                    print(x)
                    for i in participantId:
                       if x == i:
                            kills = each['stats']['deaths']
                            print('kills')
                            print(kills)

I have looked at recursively traverse lists as a solution but I cant seem to make that work. I'm very new to python and coding so maybe there is some function im missing.


Solution

  • I would recommend using dictionary comprehension for something like this.
    For example:

    participant_data = {
            _id: data for _id, data in \
            zip(participantId, each['participantId'])
            }
    

    will make participant_data a dictionary where the keys are the items in participantId, and the values are the items in each['participantId']. To get the data for a specific id, you just need to use participant_data[id_of_participant].