开始使用免费开始使用

从字典中解析数据

当 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}")
编辑并运行代码