Question: 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?

Answer: 
> 
> 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'} ]

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