Phân tích dữ liệu từ dictionary
Khi dữ liệu JSON được nạp vào bộ nhớ, dictionary kết quả có thể khá phức tạp. Các cặp key–value có thể chứa một dictionary khác, được gọi là dictionary lồng nhau (nested). Bạn sẽ thường xuyên gặp cấu trúc này khi làm việc với API hoặc dữ liệu JSON. Trong bài tập này, bạn sẽ luyện tập cách trích xuất dữ liệu từ dictionary lồng nhau và xử lý giá trị thiếu.
Dictionary bên dưới được lưu trong biến school. Chúc bạn thành công!
{
"street_address": "111 Columbia Street",
"city": "Manhattan",
"scores": {
"math": 657,
"reading": 601
}
}
Bài tập này là một phần của khóa học
ETL và ELT với Python
Hướng dẫn bài tập
- Trích xuất giá trị tại key
"street_address"từ dictionaryschool. - Trích xuất giá trị tại key
"scores"từ dictionaryschool. - Trích xuất các giá trị tại các key
"math","reading"và"writing"từ dictionaryscores, đồng thời đặt giá trị mặc định là 0.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
# 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}")