ecline6
ecline6

Reputation: 896

Joining values of two dicts by matching key value

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

Answers (4)

BonJean
BonJean

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

Óscar López
Óscar López

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

Rohit Jain
Rohit Jain

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

Ashwini Chaudhary
Ashwini Chaudhary

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

Related Questions