import requests
url = "https://api.gametools.network/bf1/players/?gameId=7218126050214"
r = requests.get(url)
data = r.json()
print(data['teams'][1]['players'][0]['name'])
print(data['teams'][1]['players'][1]['name'])
print(data['teams'][1]['players'][2]['name'])
print(data['teams'][1]['players'][3]['name'])
print(data['teams'][1]['players'][4]['name'])
print(data['teams'][1]['players'][5]['name'])
print(data['teams'][1]['players'][6]['name'])
print(data['teams'][1]['players'][7]['name'])
print(data['teams'][1]['players'][8]['name'])
print(data['teams'][1]['players'][9]['name'])
print(data['teams'][1]['players'][10]['name'])
print(data['teams'][1]['players'][11]['name'])
print(data['teams'][1]['players'][12]['name'])
print(data['teams'][1]['players'][13]['name'])
print(data['teams'][1]['players'][14]['name'])
print(data['teams'][1]['players'][15]['name'])
print(data['teams'][1]['players'][16]['name'])
print(data['teams'][1]['players'][17]['name'])
print(data['teams'][1]['players'][18]['name'])
print(data['teams'][1]['players'][19]['name'])
print(data['teams'][1]['players'][20]['name'])
This is a snippet of my code that I think could be really improved to save some space, the issue is I can't seem to find a way to enumerate all the players name beside doing them one per one like shown above, my goal is to have a list that will show every username for both team of a given server.
I should mention the code is currently working but I feel like there is a much simpler way to obtain the data I need, I did search for these methods but because my data is nested in a list/dictionary I get confused.
Any suggestion is welcome, thank you :)
CodePudding user response:
Here is how to iterate over a list:
l = [1, 2, 3, 4]
for element in l:
print(l)
Once you know that, it's only a matter of breaking nested iteration problems down to their simplest form above. So you just need to get the list which you need to iterate over, and then use the above sample you already know:
l = data['teams'][1]['players']
for element in l:
print(element['name'])
CodePudding user response:
Let's write a simple function that accepts the data from a team and use a for loop to iterate over the players.
def printTeamNames(team):
print(team["teamid"])
for player in team["players"]: print(player["name"])
Then we can pass that function that data for each team.
printTeamNames(data["teams"][0])
printTeamNames(data["teams"][1])