Javier Novoa C. Javier Novoa C. - 4 months ago 29
Python Question

Python append dictionary to dictionary

I have two existing dictionaries, and I wish to 'append' one of them to the other. By that I mean that the key,values of the other dictionary should be made into the first dictionary. For example:

orig = {
'A': 1,
'B': 2,
'C': 3,
}

extra = {
'D': 4,
'E': 5,
}

dest = # something here involving orig and extra

print dest
{
'A': 1,
'B': 2,
'C': 3,
'D': 4,
'E': 5
}


I think this all can be achieved through a for loop (maybe?) but is there some method in the dictionaries or any other module that saves this job for me? The actual dictionaries I'm using are really big...

Answer

You can do

orig.update(extra)

or, if you don't want orig to be modified, make a copy first:

dest = dict(orig)  # or orig.copy()
dest.update(extra)

Note that if extra and orig have overlapping keys, the final value will be taken from extra. For example,

>>> d1 = {1: 1, 2: 2}
>>> d2 = {2: 'ha!', 3: 3}
>>> d1.update(d2)
>>> d1
{1: 1, 2: 'ha!', 3: 3}
Comments