Coder Perfect

In Python, how do you concatenate two dictionaries to make a new one? [duplicate]

Problem

Assume I have three dictations.

d1={1:2,3:4}
d2={5:6,7:9}
d3={10:8,13:22}

How do I integrate these three dictionaries into a new d4? i.e.:

d4={1:2,3:4,5:6,7:9,10:8,13:22}

Asked by timy

Solution #1

I favor method (2), and I strongly advise against method (1) (which requires O(N) additional auxiliary memory for the concatenated list of items temporary data structure).

Answered by Alex Martelli

Solution #2

d4 = dict(d1.items() + d2.items() + d3.items())

alternatively (and ostensibly quicker):

d4 = dict(d1)
d4.update(d2)
d4.update(d3)

The previous SO question from which both of these responses were derived can be found here.

Answered by Amber

Solution #3

To create a new dictionary with all the items, use the update() method:

dall = {}
dall.update(d1)
dall.update(d2)
dall.update(d3)

Alternatively, in a loop:

dall = {}
for d in [d1, d2, d3]:
  dall.update(d)

Answered by sth

Solution #4

Here’s a one-liner that can easily be generalized to concatenate N dictionaries (imports don’t count:):

from itertools import chain
dict(chain.from_iterable(d.items() for d in (d1, d2, d3)))

and:

from itertools import chain
def dict_union(*args):
    return dict(chain.from_iterable(d.items() for d in args))
from itertools import chain
dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3))

Output:

>>> from itertools import chain
>>> d1={1:2,3:4}
>>> d2={5:6,7:9}
>>> d3={10:8,13:22}
>>> dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3)))
{1: 2, 3: 4, 5: 6, 7: 9, 10: 8, 13: 22}

Concatenate N dicts in general:

from itertools import chain
def dict_union(*args):
    return dict(chain.from_iterable(d.iteritems() for d in args))

I realize I’m a little late to the party, but I hope this information is useful to someone.

Answered by ron rothman

Solution #5

Use the dict constructor to create a dictionary.

d1={1:2,3:4}
d2={5:6,7:9}
d3={10:8,13:22}

d4 = reduce(lambda x,y: dict(x, **y), (d1, d2, d3))

As a function

from functools import partial
dict_merge = partial(reduce, lambda a,b: dict(a, **b))

Using thedict.update() function, you may avoid the overhead of constructing intermediate dictionaries:

from functools import reduce
def update(d, other): d.update(other); return d
d4 = reduce(update, (d1, d2, d3), {})

Answered by Shea Lafayette Valentine

Post is based on https://stackoverflow.com/questions/1781571/how-to-concatenate-two-dictionaries-to-create-a-new-one-in-python