2

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]}
asked Nov 29, 2013 at 5:31
1
  • Does both of them have the same key values? Or do they differ? Commented Nov 29, 2013 at 5:35

4 Answers 4

3

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]}
answered Nov 29, 2013 at 5:36
Sign up to request clarification or add additional context in comments.

Comments

1

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!

answered Nov 29, 2013 at 5:54

Comments

1
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
answered Nov 29, 2013 at 5:53

1 Comment

As far as I see, this one will not work if there some keys in dict2 that are not in dict1
0

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.

answered Nov 29, 2013 at 5:36

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.