การดึงข้อมูลจาก dictionary
เมื่อโหลดข้อมูล JSON เข้าสู่หน่วยความจำ dictionary ที่ได้อาจมีโครงสร้างที่ซับซ้อน เนื่องจากคู่ key-value บางรายการอาจมี dictionary ซ้อนอยู่ภายในอีกชั้น ซึ่งเรียกว่า nested dictionary รูปแบบนี้พบบ่อยเมื่อทำงานกับ API หรือข้อมูล JSON ทั่วไป ในแบบฝึกหัดนี้ จะได้ฝึกดึงข้อมูลจาก nested dictionary และจัดการกับค่าที่หายไป
ข้อมูลด้านล่างนี้ถูกเก็บไว้ในตัวแปร school โชคดีนะ!
{
"street_address": "111 Columbia Street",
"city": "Manhattan",
"scores": {
"math": 657,
"reading": 601
}
}
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
ETL และ ELT ด้วย Python
คำแนะนำการฝึกหัด
- ดึงค่าที่เก็บอยู่ใน key
"street_address"จาก dictionaryschool - ดึงค่าที่เก็บอยู่ใน key
"scores"จาก dictionaryschool - ดึงค่าที่เก็บอยู่ใน key
"math","reading"และ"writing"จาก dictionaryscoresและกำหนดค่าเริ่มต้นเป็น 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}")