私はこのような2つの辞書を持っています:
dict1 = {'foo': {'something':'x'} }
dict2 = {'foo': {'otherthing':'y'} }
値を結合して、次のようにします。
dict3 = {'foo': {'something':'x', 'otherthing':'y'} }
これどうやってするの?
注: 両方の dict には常に一致するキーがあります。
私はこのような2つの辞書を持っています:
dict1 = {'foo': {'something':'x'} }
dict2 = {'foo': {'otherthing':'y'} }
値を結合して、次のようにします。
dict3 = {'foo': {'something':'x', 'otherthing':'y'} }
これどうやってするの?
注: 両方の dict には常に一致するキーがあります。
辞書内包表記を試すことができます:
>>> dict1 = {'foo': {'something':'x'} }
>>> dict2 = {'foo': {'otherthing':'y'} }
>>>
>>> {key: dict(dict1[key], **dict2[key]) for key in dict1}
{'foo': {'otherthing': 'y', 'something': 'x'}}
>>> # ---Or---
>>> {keys: dict(dict1[keys].items() + dict2[keys].items()) for keys in dict1}
{'foo': {'otherthing': 'y', 'something': 'x'}}
辞書をマージするために 2 つの異なる方法を使用するだけです。
使用できますcollections.defaultdict
:
>>> from collections import defaultdict
>>> dic = defaultdict(dict)
for k in dict1:
dic[k].update(dict1[k])
dic[k].update(dict2[k])
...
>>> dic
defaultdict(<type 'dict'>,
{'foo': {'otherthing': 'y', 'something': 'x'}
})
for ループを使用して実行することもできます。
>>> dict3 = {}
>>> for x in dict1.keys():
for y in dict1[x].keys():
for z in dict2[x].keys():
dict3[x] = {y: dict1[x][y], z: dict2[x][z]}
>>> dict3
{'foo': {'otherthing': 'y', 'something': 'x'}}