20

I have two dictionaries as follows:

D1={'a':1,'b':2,'c':3}

and

D2={'b':2,'c':3,'d':1}

I want to merge these two dictionaries and the result should be as follows:

D3={'a':1,'b':2,'c':3,'b':2,'c':3,'d':1}

how can I achieve this in python?

2
  • 6
    {'a':1,'b':2,'c':3,'b':2,'c':3,'d':1} is not a Python dictionary.
    – eumiro
    Commented Sep 20, 2012 at 11:46
  • what is it -am facing a similar issue
    – El_1988
    Commented Jul 23, 2020 at 23:27

5 Answers 5

11

I want to merge these two dictionaries and the result should be as follows:

D3={'a':1,'b':2,'c':3,'b':2,'c':3,'d':1}

how can I achieve this in python?

You can't. You can only have one value per key in a Python dict. What you can do is to have a list or a set as the value.

Here is an example with a set:

d1 = { 'a': 1, 'b': 2, 'c': 3 }
d2 = { 'a': 1, 'b': 5, 'd': 4 }
d3 = {}
def add_dict(target, d):
    for key in d:
        target.setdefault(key, set([])).add(d[key])

add_dict(d3, d1)
add_dict(d3, d2)

This will give you d3:

{'a': set([1]), 'c': set([3]), 'b': set([2, 5]), 'd': set([4])}

You can also do this with a list (possibly closer to your example):

d1 = { 'a':1, 'b':2, 'c': 3}
d2 = { 'b':2 ,'c':3, 'd': 1}
d3 = {}
def add_dict(target, d):
    for key in d:
        target.setdefault(key, []).append(d[key])

add_dict(d3, d1)
add_dict(d3, d2)

You'll get this:

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

However, looking at {'a':1,'b':2,'c':3,'b':2,'c':3,'d':1} (which can't be a dict), it seems that you're after a different data structure altogether. Perhaps something like this:

d1 = { 'a':1, 'b':2, 'c': 3}
d2 = { 'b':2 ,'c':3, 'd': 1}
result = []

result += [ { 'key': key, 'value': d1[key] } for key in d1 ]
result += [ { 'key': key, 'value': d2[key] } for key in d2 ]

This would produce this, which looks closer to the data structure you had in mind initially:

[ {'value': 1, 'key': 'a'},
  {'value': 3, 'key': 'c'},
  {'value': 2, 'key': 'b'},
  {'value': 3, 'key': 'c'},
  {'value': 2, 'key': 'b'},
  {'value': 1, 'key': 'd'} ]
2
  • I tested this and seem to be missing something, as I literally typed: type({0.8080260303687652: 2e-05, 0.8069414316702677: 1e-05, 0.8091106290672485: 1e-05, 0.8156182212581342: 1e-05}) , and got the result 'dict'. So apparently it can be a dictionary?
    – El_1988
    Commented Jul 23, 2020 at 23:33
  • @El_1988 unless I'm missing something, all the keys are different in your example. You only have one value per key.
    – Bruno
    Commented Jul 24, 2020 at 8:58
6

You may want to try:

D3 = {}
D3.update(D1)
D3.update(D2)

Here, we're creating an empty dictionary D3 first, then update it from the two other dictionaries.

Note that you need to be careful with the order of the updates: if D2 shares some keys with D1, the code above will overwrite the corresponding entries of D1 with those of D2.

Note as well that the keys will not be repeated. The example you give D3={a:1,b:2,c:3,b:2,c:3,d:1} is not a valid dictionary.

1
  • +1 -- But if you type D3={a:1,b:2,c:3,b:2,c:3,d:1} into the interpreter, It'll happily allow it (provided that a,b,c,d are defined and hashable). It is a valid expression to construct a dictionary as far as I know (although I'm not sure if the standard explicitly states whether you take the first value for a repeated key or the last one, or if it is "random").
    – mgilson
    Commented Sep 20, 2012 at 12:32
4

Dictionaries by definition can't have duplicate keys, so "merging" dictionaries will actually give the following result (note the order is arbitrary):

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

You can create a clone of one of the dictionaries and merge the entries from the other into it:

D3 = dict(D1)
D3.update(D2)

or you can create a new dictionary from the concatenation of the (key, value) tuples from each input dictionary:

D3 = dict(D1.items() + D2.items())

If you really want multiple values for duplicate keys, you need something like a list of values for each key:

from itertools import groupby
dict(( (key, [v for k, v in group]) for key, group in groupby(sorted(D1.items() + D2.items()), lambda x: x[0])))
2

What are you asking is not possible, since you cannot have two different keys with the same value in a Python dictionary.

The closest answer to your question is:

D3 = dict( D1.items() + D2.items() )

Note: if you have different values for the same key, the ones from D2 will be the ones in D3.

Example:
D1 = { 'a':1, 'b'=2 }
D2 = { 'c':3, 'b':3}
Then, D3 will be:
D3= { 'a':1, 'b':3, 'c':3 }

2
In [3]: D1={'a':1,'b':2,'c':3}

In [4]: D2={'b':2,'c':3,'d':1}

In [5]: D1.update(D2)

In [6]: D1
Out[6]: {'a': 1, 'b': 2, 'c': 3, 'd': 1}

Update

Alternative solutions

In [9]: D3=D1.copy()

In [10]: D3.update(D2)

In [11]: D3
Out[11]: {'a': 1, 'b': 2, 'c': 3, 'd': 1}

In [12]: D4=dict(D1, **D2)

or

In [13]: D4
Out[13]: {'a': 1, 'b': 2, 'c': 3, 'd': 1}

or

In [16]: D5 = dict(D1.items() + D2.items())

In [17]: D5
Out[17]: {'a': 1, 'b': 2, 'c': 3, 'd': 1}
2
  • 1
    ... which modifies D1. It may be wiser to make a copy first.
    – Pierre GM
    Commented Sep 20, 2012 at 11:44
  • true, just a quick session in ipython; 4 more or less identical answers here :-) Commented Sep 20, 2012 at 11:45

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