Reputation: 77
my question is about this list that i have. In the list are 2 things: "meta-data" and "players" in "players" is "all_players". Now i want to get the Player Name and Player Team but i dont know how i can do this. i can do data["data"][i]['players']['all_players'][{name}]
but then i only have the name, and i cant get the team when i dont know which player the team i should get.
Here is my List:
{
"data": [
{
"metadata": {
"map": "Breeze",
"game_length": 1702289,
"game_start": 1657464507,
"game_start_patched": "Sunday, July 10, 2022 4:48 PM",
"rounds_played": 20,
"mode": "Competitive",
"queue": "Standard",
"platform": "PC",
"region": "eu",
"cluster": "London"
},
"players": {
"all_players": [
{
"puuid": "70f7373a-ba78-5c9a-a963-767fbf27d9ad",
"name": "Player 1",
"team": "Blue"
},
{
"puuid": "70f7373a-ba78-5c9a-a963-767fbf27d9ad",
"name": "Player 2",
"team": "Blue"
},
{
"puuid": "70f7373a-ba78-5c9a-a963-767fbf27d9ad",
"name": "Player 3",
"team": "Red"
},
]}
}]
}
This is only a small part, where things are what i want to have. The List is way longer but its unnecessary for this part This List or Data is from a JSON.
Upvotes: 2
Views: 342
Reputation: 9379
Here's a way to do what your question asks:
all_players = data["data"][0]["players"]["all_players"]
playerNames = [player["name"] for player in all_players]
teamNames = [player["team"] for player in all_players]
teamByPlayer = {player["name"]:player["team"] for player in all_players}
Output
playerNames
['Player 1', 'Player 2', 'Player 3']
teamNames
['Blue', 'Blue', 'Red']
teamByPlayer
{'Player 1': 'Blue', 'Player 2': 'Blue', 'Player 3': 'Red'}
Explanation:
playerNames
and teamNames
each use a list comprehension
to create a list based on the items in the for
loop.teamNames
uses a dict comprehension
to add a key:value pair using key player["name"]
and value player["team"]
for each player
in the for
loop.To find the team for a given player, you can do this using accumulate()
:
from itertools import accumulate
def findTeamOfPlayer(player):
all_players = data["data"][0]["players"]["all_players"]
team = list(accumulate(p["team"] for p in all_players if p["name"] == player))
return team[0] if team else None
target = "Player 2"
team = findTeamOfPlayer("Player 2")
print(team)
team = findTeamOfPlayer("Player 99")
print(team)
Output:
Blue
None
Upvotes: 2