Matt
Matt

Reputation: 189

Looping through nested dictionary

I am attempting to get data from a JSON file found at https://fantasy.premierleague.com/drf/event/19/live. However, I'm running into a problem whenever I loop through the data received.

The first loop in my code below should be appending the value in data["elements"]["1"]["stats"]["goals_scored"], but I'm getting the error string indices must be integers whenever I run this the code below. Whenever I reference data["elements"]["number"]["stats"]["goals_scored"]directly, it returns the correct number just fine.

import json
import requests

def goalCalculator():
    data=requests.get("https://fantasy.premierleague.com/drf/event/19/live").json()
    list1=[]
    for i in data["elements"]:
        list1.append(i["stats"]["goals_scored"])
    return list1

goalCalculator()

I have mapped the JSON file out (below), but I can't see where I'm going wrong. Shouldn't my code be working fine?

"elements":{
    "1":{
        "stats":{
            "yellow_cards":0,
            "own_goals":0,
            "creativity":0.0,
            "goals_conceded":0,
            "bonus":0,
            "red_cards":0,
            "saves":0,
            "influence":0.0,
            "bps":0,
            "clean_sheets":0,
            "assists":0,
            "ict_index":0.0,
            "goals_scored":0,
            "threat":0.0,
            "penalties_missed":0,
            "total_points":0,
            "penalties_saved":0,
            "in_dreamteam":false,
            "minutes":0
        }
    },
    "2":{etc...

Upvotes: 1

Views: 91

Answers (2)

Sahil Shah
Sahil Shah

Reputation: 96

Instead of

for i in data["elements"]:
    list1.append(i["stats"]["goals_scored"])

use

for i in data["elements"]:
    list1.append(data["elements"][i]["stats"]["goals_scored"])

The i in the loop is the key of the data["elements"] dictionary and not the complete element as you are assuming. It would simply be "1" in your example, so you cannot index that. You will need to get the complete element which will be data["elements"][i]

Upvotes: 1

Mark Keane
Mark Keane

Reputation: 1044

for i in data["elements"]:

The above does not loop through the elements in the dictionary, instead it loops through the keys. I would do something like this:

import json
import requests

def goalCalculator():
    data=requests.get("https://fantasy.premierleague.com/drf/event/19/live").json()
    list1=[]
    for key, value in data["elements"].iteritems():
        list1.append(value["stats"]["goals_scored"])
    return list1

goalCalculator()

If you do not need the keys at all for what you are doing, you can use (as suggested by the helpful user who commented on my answer) .values() like so:

import json
import requests

    def goalCalculator():
        data=requests.get("https://fantasy.premierleague.com/drf/event/19/live").json()
        list1=[]
        for nested_dict in data["elements"].values():
            list1.append(nested_dict["stats"]["goals_scored"])
        return list1

    goalCalculator()

Upvotes: 2

Related Questions