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