Combining two dictionaries while maintaining the original

In Python, when I combine two dictionaries using the update () method, any existing keys will be overwritten.

Is there a way to combine two dictionaries while keeping the original keys in a combined result?

Update

Let's say we had the following example:

dict1 = {'bookA': 1, 'bookB': 2, 'bookC': 3} dict2 = {'bookC': 2, 'bookD': 4, 'bookE': 5} 

Is it possible to combine two dictionaries so that the result retains both values ​​for the bookC key?

I would like dict3 look like this:

 {'bookA': 1, 'bookB': 2, 'bookC': (2,3), 'bookD': 4, 'bookE': 5} 
+9
source share
4 answers

If it’s convenient to save all the values ​​as a list (which I would prefer, it just adds extra headache and logic when your value data types are incompatible), you can use the approach below for your updated example using defaultdict

 from itertools import chain from collections import defaultdict d1 = {'a': 1, 'b': 2, 'c': 3} d2 = {'a': 2, 'b': 3, 'd': 4} d3 = defaultdict(list) for k, v in chain(d1.items(), d2.items()): d3[k].append(v) for k, v in d3.items(): print(k, v) 

Print

 a [1, 2] d [4] c [3] b [2, 3] 

You also have the approach below, which I find slightly less readable:

 d1 = {'a': 1, 'b': 2, 'c': 3} d2 = {'a': 2, 'b': 3,} d3 = dict((k, [v] + ([d2[k]] if k in d2 else [])) for (k, v) in d1.items()) print(d3) 

This will not change any of the source dictionaries and print:

 {'b': [2, 3], 'c': [3], 'a': [1, 2]} 
+10
source
 a = {'a': 1, 'b': 2, 'c': 3} b = {'a': 10, 'd': 2, 'e': 3} b.update({key: (a[key], b[key]) for key in set(a.keys()) & set(b.keys())}) b.update({key: a[key] for key in set(a.keys()) - set(b.keys())}) print(b) 

Output: {'c': 3, 'd': 2, 'e': 3, 'b': 2, 'a': (1, 10)}

+2
source
 a = {'a': 1, 'b': 2, 'c': 3} b = {'a': 10, 'd': 2, 'e': 3} for k in b: if k not in a: a[k] = b[k] 

Update

After updating the question, I agree to doing BAH using defaultdict with a list

+1
source

There is another way to save all values ​​as a list that does not use defaultdict or chaining.

Review the example:

 d1 = {'a': 1, 'b': 2, 'c': 3} d2 = {'a': 2, 'b': 3, 'd': 4} d3 = {} for (k, v) in list(d1.items())+list(d2.items()): try: d3[k] += [v] except KeyError: d3[k] = [v] print(d3) 

Then we have:

 {'d': [4], 'b': [2, 3], 'a': [1, 2], 'c': [3]} 

The try statement is used for speed. He is trying to add the value of v using the key k. In the case of KeyError, d3 accepts a new key.

+1
source

All Articles