辞書からのデータ解析
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}")