Aan de slagBegin gratis

Gegevens parsen uit dictionaries

Wanneer JSON-gegevens in het geheugen worden geladen, kan de resulterende dictionary ingewikkeld zijn. Sleutel-waardeparen kunnen een andere dictionary bevatten; zulke structuren noem je geneste dictionaries. Deze geneste dictionaries kom je vaak tegen bij het werken met API's of andere JSON-gegevens. In deze oefening ga je data uit geneste dictionaries halen en ontbrekende waarden afhandelen.

De onderstaande dictionary staat in de variabele school. Succes!

{
    "street_address": "111 Columbia Street",
    "city": "Manhattan",
    "scores": {
        "math": 657,
        "reading": 601
    }
}

Deze oefening maakt deel uit van de cursus

ETL en ELT in Python

Bekijk cursus

Oefeninstructies

  • Parse de waarde bij de sleutel "street_address" uit de dictionary school.
  • Parse de waarde bij de sleutel "scores" uit de dictionary school.
  • Parse de waarden bij de sleutels "math", "reading" en "writing" uit de dictionary scores, en stel de standaardwaarde in op 0.

Interactieve oefening met praktijkervaring

Probeer deze oefening door deze voorbeeldcode aan te vullen.

# Parse the street_address from the dictionary
street_address = school.____("street_address")

# Parse the scores dictionary
scores = school.____("____")

# Try to parse the math, reading and writing values from scores
math_score = scores.____("math", ____)
reading_score = scores.____
writing_score = ____

print(f"Street Address: {street_address}")
print(f"Math: {math_score}, Reading: {reading_score}, Writing: {writing_score}")
Code bewerken en uitvoeren