fuhrerguxez fuhrerguxez - 15 days ago 9
Python Question

Python - How to get an item out of a list of dicts?

Right now (If I'm not wrong) I have a list of dicts with some information; I want to get an specific item out of the list but I am having a problem to reach the item that I want; this is what I'm trying:

stats = requests.get("https://lan.api.pvp.net/api/lol/lan/v1.3/stats/by-summoner/24244/"
"summary?season=SEASON2016&api_key=").json()

pprint([d['playerStatSummaries'] for d in stats if 'playerStatSummaryType' in d])


I tried that by watching some examples; it may work but maybe I'm doing in the wrong way, the output of that is just a "[ ]" the request has this information:

"summonerId": 24244,
"playerStatSummaries": [

{
"playerStatSummaryType": "CAP5x5",
"wins": 20,
"modifyDate": 1453305771000,
"aggregatedStats": {
"totalChampionKills": 308,
"totalMinionKills": 4985,
"totalTurretsKilled": 36,
"totalNeutralMinionsKilled": 466,
"totalAssists": 255
}
},
{
"playerStatSummaryType": "CoopVsAI",
"wins": 34,
"modifyDate": 1453305771000,
"aggregatedStats": {
"totalChampionKills": 394,
"totalMinionKills": 2741,
"totalTurretsKilled": 57,
"totalNeutralMinionsKilled": 146,
"totalAssists": 336
}
},
{
"playerStatSummaryType": "CoopVsAI3x3",
"wins": 1,
"modifyDate": 1453305771000,
"aggregatedStats": {
"totalChampionKills": 6,
"totalMinionKills": 69,
"totalTurretsKilled": 2,
"totalNeutralMinionsKilled": 0,
"totalAssists": 3
}
},
{
"playerStatSummaryType": "RankedTeam3x3",
"wins": 0,
"losses": 0,
"modifyDate": 1353893998000,
"aggregatedStats": { }
},
{
"playerStatSummaryType": "RankedTeam5x5",
"wins": 0,
"losses": 0,
"modifyDate": 1354061714000,
"aggregatedStats": { }
}


Let's say that I want to access the information of "CoopVsAI" which is the second one; from that I want to access the "totalChampionKills"; how can I do that? Because they are nested so I'm not sure on how to do it. I tried doing

for key, value in stats['playerStatSummaries'].items():
if key['playerStatSummaryType'] == "Unranked":
# do something


But that didn't work, so; that's it, thanks for any help you can provide :)

Answer

"playerStatSummaries" holds list value and not dict. Hence your for loop should be like:

#         v  This will be `dict` object
for player_stat_summary in stats['playerStatSummaries']:
    if player_stat_summary['playerStatSummaryType'] == "Unranked":
        # Do Something

        # player_stat_summary['aggregatedStats']['totalChampionKills']
        # For accessing the value you require