複数の値を保持するには、リストの辞書を使用します。
キーに複数の値を持たせる 1 つの方法は、リストの辞書を使用することです。
x = { 'Key1' : ['Hello', 'World'],
'Key2' : ['Howdy', 'Neighbor'],
'Key3' : ['Hey', 'Dude']
}
必要なリストを取得する (または新しいリストを作成する) には、setdefault を使用することをお勧めします。
my_list = x.setdefault(key, [])
例:
>>> x = {}
>>> x['abc'] = [1,2,3,4]
>>> x
{'abc': [1, 2, 3, 4]}
>>> x.setdefault('xyz', [])
[]
>>> x.setdefault('abc', [])
[1, 2, 3, 4]
>>> x
{'xyz': [], 'abc': [1, 2, 3, 4]}
defaultdict
同じ機能に使用
これをさらに簡単にするために、collections モジュールにはこれを単純化するdefaultdict
オブジェクトがあります。コンストラクター/ファクトリーを渡すだけです。
from collections import defaultdict
x = defaultdict(list)
x['key1'].append(12)
x['key1'].append(13)
辞書の辞書やセットの辞書を使用することもできます。
>>> from collections import defaultdict
>>> dd = defaultdict(dict)
>>> dd
defaultdict(<type 'dict'>, {})
>>> dd['x']['a'] = 23
>>> dd
defaultdict(<type 'dict'>, {'x': {'a': 23}})
>>> dd['x']['b'] = 46
>>> dd['y']['a'] = 12
>>> dd
defaultdict(<type 'dict'>, {'y': {'a': 12}, 'x': {'a': 23, 'b': 46}})