JSONデータの変換
JSON形式から辞書にデータを読み込むとき、DataFrameに保存できる形にする前に、何らかの手動変換が必要になることがよくあります。入れ子構造の辞書を扱う場合に特によくあることで、この演習ではその例を体験します。
"nested_school_scores.json" ファイルは辞書に読み込まれ、raw_testing_scores という変数で利用できます。構造は次のとおりです。
{
"01M539": {
"street_address": "111 Columbia Street",
"city": "Manhattan",
"scores": {
"math": 657,
"reading": 601,
"writing": 601
}
}, ...
}
この演習はコースの一部です
Python で学ぶ ETL と ELT
演習の手順
raw_testing_scores辞書のキーと値の両方をループで処理します。raw_testing_scoresオブジェクト内で入れ子になっている各辞書から"street_address"を取り出します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
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)