從字典解析資料
當 JSON 資料載入到記憶體後,得到的字典可能很複雜。鍵值配對中還可能包含另一個字典,這類稱為巢狀字典。處理 API 或其他 JSON 資料時,經常會遇到巢狀字典。在本練習中,你會練習從巢狀字典擷取資料,並處理遺漏值。
以下的字典已存放在變數 school 中。加油!
{
"street_address": "111 Columbia Street",
"city": "Manhattan",
"scores": {
"math": 657,
"reading": 601
}
}
本練習屬於課程
使用 Python 的 ETL 與 ELT
練習說明
- 從字典
school中解析鍵"street_address"所儲存的值。 - 從字典
school中解析鍵"scores"所儲存的值。 - 從字典
scores中解析鍵"math"、"reading"、"writing"的值,並將預設值設為 0。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# 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}")