Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two dictionaries while keeping the original

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

Is there a way to merge the two dictionaries while keeping the original keys in the merged result?

Say we had the following example:

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

Can we merge the two dictionaries, such that the result will keep both values for the key bookC?

I'd like dict3 to look like this:

{'bookA': 1, 'bookB': 2, 'bookC': (2,3), 'bookD': 4, 'bookE': 5}
like image 562
Simplicity Avatar asked Mar 23 '16 14:03

Simplicity


People also ask

Can you merge two dictionaries?

You can merge two dictionaries by iterating over the key-value pairs of the second dictionary with the first one.

How do I merge two dictionaries in a single expression?

Using | in Python 3.9 In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.

Which function helps merge dictionary?

Dictionary is also iterable, so we can use itertools. chain() to merge two dictionaries. The return type will be itertools.


2 Answers

If it's alright to keep all values as a list (which I would prefer, it just adds extra headache and logic when your value data types aren't consistent), you can use the below approach for your updated example using a 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)

Prints:

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

You also have the below approach, which I find a little 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 wont modify any of the original dictionaries and print:

{'b': [2, 3], 'c': [3], 'a': [1, 2]}
like image 62
Bahrom Avatar answered Oct 30 '22 07:10

Bahrom


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)}

like image 21
Stephen Briney Avatar answered Oct 30 '22 07:10

Stephen Briney