始める無料で始める

辞書からのデータ解析

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}")
コードを編集して実行