เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การแปลงข้อมูล JSON

เมื่ออ่านข้อมูลจากรูปแบบ JSON เข้ามาเป็นดิกชันนารี มักต้องมีการแปลงข้อมูลด้วยตนเองในระดับหนึ่งก่อนจะนำไปเก็บใน DataFrame ได้ กรณีนี้พบได้บ่อยเมื่อทำงานกับดิกชันนารีแบบซ้อน (nested dictionaries) ซึ่งคุณจะได้ลองฝึกในแบบฝึกหัดนี้

ไฟล์ "nested_school_scores.json" ถูกอ่านเข้ามาเป็นดิกชันนารีและเก็บไว้ในตัวแปร raw_testing_scores ซึ่งมีรูปแบบดังนี้:

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

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

ETL and ELT ใน Python

ดูคอร์ส

คำแนะนำการฝึกหัด

  • วนลูปผ่านทั้งคีย์และค่าของดิกชันนารี raw_testing_scores
  • ดึงค่า "street_address" จากแต่ละดิกชันนารีที่ซ้อนอยู่ในออบเจ็กต์ raw_testing_scores

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

normalized_testing_scores = []

# Loop through each of the dictionary key-value pairs
for school_id, school_info in raw_testing_scores.____():
	normalized_testing_scores.append([
    	school_id,
    	school_info.____("____"),  # Pull the "street_address"
    	school_info.get("city"),
    	school_info.get("scores").get("math", 0),
    	school_info.get("scores").get("reading", 0),
    	school_info.get("scores").get("writing", 0),
    ])

print(normalized_testing_scores)
แก้ไขและรันโค้ด