Reputation: 896
I have two dictionaries like this:
dict1 = {'foo': {'something':'x'} }
dict2 = {'foo': {'otherthing':'y'} }
and i want to join the values together so that:
dict3 = {'foo': {'something':'x', 'otherthing':'y'} }
How can I do this?
Note: both dicts will always have matching keys.
Upvotes: 2
Views: 184
Reputation: 11
It can also be done using for loops:
>>> 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'}}
Upvotes: 1
Reputation: 236114
Another option, as a shorter one-liner dictionary comprehension:
{ k : dict(dict2[k].items() + v.items()) for k, v in dict1.items() }
Upvotes: 1
Reputation: 213331
You can try using dict comprehension:
>>> 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'}}
they just use two different ways to merge dicts.
Upvotes: 4
Reputation: 251096
You can use 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'}
})
Upvotes: 2