Spock
Spock

Reputation: 505

Merge 2 dictionaries in Python without deleting first dictionary

How can i merge dict1 and dict2 so that i get res? Preferably using .update()

dict1 = {'a':[1, 2, 3], 'b':[4, 5, 6]}
dict2 = {'a':[100, 101, 103], 'b':[104, 105, 106]}
res = {'a':[1, 2, 3, 100, 101, 103], 'b':[4, 5, 6, 104, 105, 106]}

Upvotes: 2

Views: 93

Answers (4)

BlackMamba
BlackMamba

Reputation: 10252

dict1 = {'a':[1, 2, 3], 'b':[4, 5, 6]}
dict2 = {'a':[100, 101, 103], 'b':[104, 105, 106]}
def combine(D1, D2):
    D = collections.defaultdict(list)
    for k, v in D1.items():
        D[k] += v
        D[k] += D2[k]
    return D

Upvotes: 1

William
William

Reputation: 1007

If the dictionaries have the same keys, I think this is the simplest solution:

res = {k : dict1[k]+dict2[k] for k in dict1}

If the dictionaries have different keys, but you only care about the keys which are the same:

res = {k : dict1[k]+dict2[k] for k in set(dict1) & set(dict2)}

Otherwise, another answer will do!

Upvotes: 1

roman
roman

Reputation: 117520

If dicts have same keys:

>>> {k: v + dict2.get(k, []) for k, v in dict1.iteritems()}
{'a': [1, 2, 3, 100, 101, 103], 'b': [4, 5, 6, 104, 105, 106]}

if not:

>>> from itertools import chain
>>> res = {}
>>> for k, v in chain(dict1.iteritems(), dict2.iteritems()):
...     res[k] = res.get(k, []) + v
... 
>>> res
{'a': [1, 2, 3, 100, 101, 103], 'b': [4, 5, 6, 104, 105, 106]}

and you can use collections.defaultdict in this solution:

>>> from collections import defaultdict
>>> res = defaultdict(list)
>>> for k, v in chain(dict1.iteritems(), dict2.iteritems()):
...     res[k] += v
... 
>>> dict(res)
{'a': [1, 2, 3, 100, 101, 103], 'b': [4, 5, 6, 104, 105, 106]}

Upvotes: 3

Pita
Pita

Reputation: 1474

this assumes dict1 and dict2 has the same keys

res = {}
for i in dict1.keys()
    res[i] = dict1[i] + dict2[i]

something like that should work, i didn't run the code so it might be wrong but the idea should be correct.

Upvotes: 0

Related Questions