Reputation: 37
I have a nested dictionary that is the match list of recent games played. Let's say this dictionary (match list) is stored in the variable m
. Here's the contents:
{
"matches": [
{
"platformId": "NA1",
"gameId": 3000208798,
"champion": 7,
"queue": 420,
"season": 13,
"timestamp": 1552770736282,
"role": "SOLO",
"lane": "MID"
},
{
"platformId": "NA1",
"gameId": 3000221890,
"champion": 2,
"queue": 420,
"season": 13,
"timestamp": 1552768857241,
"role": "NONE",
"lane": "JUNGLE"
},
{
"platformId": "NA1",
"gameId": 2999711945,
"champion": 72,
"queue": 420,
"season": 13,
"timestamp": 1552722174457,
"role": "NONE",
"lane": "JUNGLE"
},
{
"platformId": "NA1",
"gameId": 2999696777,
"champion": 60,
"queue": 420,
"season": 13,
"timestamp": 1552720181393,
"role": "NONE",
"lane": "JUNGLE"
},
{
"platformId": "NA1",
"gameId": 2999691752,
"champion": 7,
"queue": 420,
"season": 13,
"timestamp": 1552718383760,
"role": "SOLO",
"lane": "MID"
}
],
"startIndex": 0,
"endIndex": 5,
"totalGames": 66
}
The match list contains 5 matches or games, and I have been trying to write a function that gets all 5 gameId
s and returns them in the form of a list
.
I tried something like:
def getGameIds():
gameIds = []
for "gameId" in m:
gameIds.append(m.get("gameId"))
return gameIds
Thinking that I could loop through each occurrence of the key "gameId"
, but I have not had any luck.
Upvotes: 0
Views: 42
Reputation: 88
Try this:
l = [v for k,v in m.items() if k == "matches"]
glist = [i['gameId'] for d in l for i in d]
Upvotes: 0
Reputation: 7509
You're close, but not quite there. Think about every element you need to access: a dictionary, then a list, then a dictionary. Try this instead:
def getGameIds():
gameIds = []
for subdict in m["matches"]:
gameIds.append(subdict.get("gameId"))
return gameIds
Upvotes: 3
Reputation: 8047
Try iterating over each entry adding to a new list:
l = [i['gameId'] for i in data['matches']]
# [i.get('gameId') for i in data['matches']] also works
Should produce list l
containing:
[3000208798, 3000221890, 2999711945, 2999696777, 2999691752]
Upvotes: 3