2

私はこのような2つの辞書を持っています:

dict1 = {'foo': {'something':'x'} }
dict2 = {'foo': {'otherthing':'y'} }

値を結合して、次のようにします。

dict3 = {'foo': {'something':'x', 'otherthing':'y'} }

これどうやってするの?

注: 両方の dict には常に一致するキーがあります。

4

4 に答える 4

4

辞書内包表記を試すことができます:

>>> 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 つの異なる方法を使用するだけです。

于 2013-08-29T16:04:33.567 に答える
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'}
})
于 2013-08-29T16:02:19.273 に答える
1

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'}}
于 2013-08-29T16:21:46.950 に答える