12

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}
10
  • 3
    Can you give a sample input/output?
    – Bahrom
    Mar 23, 2016 at 14:17
  • What exactly do you want to happen to keys that are present in both dicts?
    – jwodder
    Mar 23, 2016 at 14:18
  • @BAH Thanks, added an example
    – Simplicity
    Mar 23, 2016 at 14:22
  • 4
    You can't have a dictionary contain two keys of the same value. Keys must be unique. I would question the purpose of the outer code and whether a dictionary is the correct object to store the data you need?
    – J2C
    Mar 23, 2016 at 14:27

5 Answers 5

14

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]}
7
  • 1
    What about the elements in d2 that are not in d1? Will they get to d3 with the above implementation?
    – EduardoCMB
    Mar 23, 2016 at 14:32
  • @EduardoCMB you're right they won't, I realized that when he updated his question. See edited answer with defaultdict
    – Bahrom
    Mar 23, 2016 at 14:33
  • 1
    this is the exact thing I just wrote - but the *zip call is superfluous. Also just use d3[k].append(v) Mar 23, 2016 at 14:33
  • @Simplicity, no worries, glad to have helped :)
    – Bahrom
    Mar 23, 2016 at 17:21
  • what about in one line? Jan 30, 2017 at 2:26
2
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)}

1
  • 1
    the output should have the key of both a and b Mar 23, 2016 at 14:46
1
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 the update to the question I would agree with BAH's implementation of using a defaultdict with a list

2
  • "Can we merge the two dictionaries, such that the result will keep both values for the key bookC?"
    – SiHa
    Mar 23, 2016 at 14:23
  • OK, but it doesn't answer the question as it currently stands. It happens sometimes that a question is edited to invalidate an answer. That answer should be changed or deleted.
    – SiHa
    Mar 23, 2016 at 14:25
1

There is another way to keep all values as a list, which is not using defaultdict or chain.

Revise 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. It tries to add the value v with the key k. In case of KeyError, d3 accepts the new key.

0

If you care about the ordering which I think the other answers don't quite get right. This is Python 3.9:

dict1 = {'bookA': 1, 'bookB': 2, 'bookC': 3}
dict2 = {'bookC': 2, 'bookD': 4, 'bookE': 5}
dict3 = dict1 | dict2
dict4 = {key for key in dict1 if key in dict2}
dict5 = {key: (dict1[key], dict2[key]) for key in dict4}
result = dict3 | dict5

for item in result:
    print(repr(result[item]))

print(result)


1
2
(3, 2)
4
5
{'bookA': 1, 'bookB': 2, 'bookC': (3, 2), 'bookD': 4, 'bookE': 5}

You can then use tuple unpacking:

for item in result:
    if  type(result[item]) is tuple:
        print("Value from dict1: {}, value from dict2: {}".format(*result[item]))

Value from dict1: 3, value from dict2: 2

And if you want to be crazy and put the result dict on one line:

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

result = dict1 | dict2 | {key: (dict1[key], dict2[key]) for key in {key for key in dict1 if key in dict2}}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.