I.Nested dictionaries

階層のある辞書の処理方法を学びます。

統計解析では、データがJSONファイルの場合がよくあります。

PythonではJSONを辞書に変換して扱うので、階層のある辞書の処理方法は、JSONを処理するためにも必要です。

II.For loopsの場合

次の解説で学びます。

Python Nested Dictionary: A How-To Guide

サンプルデータを作成します。“:” の左がkeyで、右がvalueです。

3つの辞書があり、0, 1, 2のvalueが辞書である入れ子型のデータです。

ice_cream_flavors = {
    0: { "flavor": "Vanilla", "price": 0.50, "pints": 20 },
    1: { "flavor": "Chocolate", "price": 0.50, "pints": 31 },
  2: { "flavor": "Cookies and Cream", "price": 0.75, "pints": 14 }
}

入れ子の辞書のkeysとvaluesを表示するコードは次です。

for key, value in ice_cream_flavors.items():
    print("Ice Cream:", key)
    for k, v in value.items():
        print(k + ":", value[k])
## Ice Cream: 0
## flavor: Vanilla
## price: 0.5
## pints: 20
## Ice Cream: 1
## flavor: Chocolate
## price: 0.5
## pints: 31
## Ice Cream: 2
## flavor: Cookies and Cream
## price: 0.75
## pints: 14

To be continued.