Home > Software design >  how to hide objects in nested dictionary
how to hide objects in nested dictionary

Time:08-28

example.json file and related python file in the below. Can we modify it please?

{
    "results": [
        {
            "leagues": [
                {
                    "matches": [
                        {
                            "league": "Premier League",
                            "teams": "Leeds - Chelsea",
                            "score": [
                                "3:0"
                            ]
                        },
                        {
                            "league": "Premier League",
                            "teams": "Man Utd - Liverpool",
                            "score": [
                                "2:1"
                            ]
                        }

                    ]
                },
                {
                    "matches": [
                        {
                            "league": "La Liga",
                            "teams": "Atletico Madrid - Villareal",
                            "score": [
                                "0:2"
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

this is py file I run

import json

with open("example2.json") as f:
    jsondata = json.load(f)

for a in jsondata["results"][0]["leagues"]:
    for b in a["matches"]:
      print(b["league"],b["teams"],b["score"][0])

this is output:

Premier League Leeds - Chelsea 3:0
Premier League Man Utd - Liverpool 2:1
La Liga Atletico Madrid - Villareal 0:2

I want to hide "teams" object has "Leeds" word and "league" object has "La Liga" name. how can I modify py file to get this output

Premier League Man Utd - Liverpool 2:1

CodePudding user response:

You can use a if condition to check like this:

for a in jsondata["results"][0]["leagues"]:
    for b in a["matches"]:
        if "leeds" not in b["teams"] and "La Liga" not in b["league"]:
            print(b["league"],b["teams"],b["score"][0])

CodePudding user response:

Check those conditions before you print and skip that iteration of the loop if either is met:

      if "Leeds" in b["teams"] or "La Liga" in b["league"]:
          continue
  • Related