Home > Software design >  for loop in nested dictionary
for loop in nested dictionary

Time:08-15

premierleague=jsondata["results"][4]["Elems"][0]
bundesliga=jsondata["results"][4]["Elems"][1]
laliga=jsondata["results"][4]["Elems"][2]

premierleaguematch1=jsondata["results"][4]["Elems"][0]["Elems"][0]
premierleaguematch2=jsondata["results"][4]["Elems"][0]["Elems"][1]
bundesligamatch1=jsondata["results"][4]["Elems"][1]["Elems"][0]
laligamatch1=jsondata["results"][4]["Elems"][2]["Elems"][0]

how can I write for loop code for this case in python? Thank you.

CodePudding user response:

list comprehension might be better in this case. Leagues and matches are in the same order except I added premierleaguematch2 separately

leagues = [jsondata["results"][4]["Elems"][i] for i in range(3)]
matches = [league["Elems"][0] for league in leagues]

# append premierleaguematch2
matches.append(leagues[0]["Elems"][1])

CodePudding user response:

It seems that your jsondata["results"][4]["Elems"] is a list of the leagues. Then, in each league, the ["Elems"] field gives you a list of matches. Therefore:

for league in jsondata["results"][4]["Elems"]:
  for match in league["Elems"]:
    print(match)

I'm not sure what exactly you want to do with the matches; here I'm just printing them, for what it's worth.

CodePudding user response:

premier league(EPL)   =jsondata["results"][4]["Elems"][0]
EPL match1 home team  =jsondata["results"][4]["Elems"][0]["Elems"][0]["opp1"]
EPL match1 away team  =jsondata["results"][4]["Elems"][0]["Elems"][0]["opp2"]
EPL match1 date       =jsondata["results"][4]["Elems"][0]["Elems"][0]["date"]
EPL match1 score      =jsondata["results"][4]["Elems"][0]["Elems"][0]["score"]

EPL match2 home team  =jsondata["results"][4]["Elems"][0]["Elems"][1]["opp1"]
EPL match2 away team  =jsondata["results"][4]["Elems"][0]["Elems"][1]["opp2"]
EPL match2 date       =jsondata["results"][4]["Elems"][0]["Elems"][1]["date"]
EPL match2 score      =jsondata["results"][4]["Elems"][0]["Elems"][1]["score"]

bundesliga(GER)       =jsondata["results"][4]["Elems"][1]
GER match1 home team  =jsondata["results"][4]["Elems"][1]["Elems"][0]["opp1"]
GER match1 away team  =jsondata["results"][4]["Elems"][1]["Elems"][0]["opp2"]
GER match1 date       =jsondata["results"][4]["Elems"][1]["Elems"][0]["date"]
GER match1 score      =jsondata["results"][4]["Elems"][1]["Elems"][0]["score"]

la liga(ESP)          =jsondata["results"][4]["Elems"][2]
ESP match1 home team  =jsondata["results"][4]["Elems"][2]["Elems"][0]["opp1"]
ESP match1 away team  =jsondata["results"][4]["Elems"][2]["Elems"][0]["opp2"]
ESP match1 date       =jsondata["results"][4]["Elems"][2]["Elems"][0]["date"]
ESP match1 score      =jsondata["results"][4]["Elems"][2]["Elems"][0]["score"]

I need to write "for" loop code in order to get output like this:

Arsenal Liverpool 2022-08-10 3-2
Chelsea Tottenham 2022-08-11 2-1
Bayern Dortmund 2022-08-12 5-0
Real Madrid Barcelona 2022-08-13 1-0
  • Related