Parsing data from dictionaries
When JSON data is loaded into memory, the resulting dictionary can be complicated. Key-value pairs may contain another dictionary, such are called nested dictionaries. These nested dictionaries are frequently encountered when dealing with APIs or other JSON data. In this exercise, you will practice extracting data from nested dictionaries and handling missing values.
The dictionary below is stored in the school
variable. Good luck!
{
"street_address": "111 Columbia Street",
"city": "Manhattan",
"scores": {
"math": 657,
"reading": 601
}
}
This exercise is part of the course
ETL and ELT in Python
Exercise instructions
- Parse the value stored at the
"street_address"
key from theschool
dictionary. - Parse the value stored at the
"scores"
key from theschool
dictionary. - Parse the values stored at the
"math"
,"reading"
, and"writing"
keys from thescores
dictionary, and set the default value to 0.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# 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}")