Adding dictionaries together

Question:

I have two dictionaries and I’d like to be able to make them one:

Something like this pseudo-Python would be nice:

dic0 = {'dic0': 0}
dic1 = {'dic1': 1}

ndic = dic0 + dic1
# ndic would equal {'dic0': 0, 'dic1': 1}
Asked By: rectangletangle

||

Answers:

You are looking for the update method

dic0.update( dic1 )
print( dic0 ) 

gives

{'dic0': 0, 'dic1': 1}
Answered By: mmmmmm
dic0.update(dic1)

Note this doesn’t actually return the combined dictionary, it just mutates dic0.

Answered By: Daniel Roseman
>>> dic0 = {'dic0':0}
>>> dic1 = {'dic1':1}
>>> ndic = dict(list(dic0.items()) + list(dic1.items()))
>>> ndic
{'dic0': 0, 'dic1': 1}
>>>
Answered By: Vijay

The easiest way to do it is to simply use your example code, but using the items() member of each dictionary. So, the code would be:

dic0 = {'dic0': 0}
dic1 = {'dic1': 1}
dic2 = dict(dic0.items() + dic1.items())

I tested this in IDLE and it works fine.
However, the previous question on this topic states that this method is slow and chews up memory. There are several other ways recommended there, so please see that if memory usage is important.

Answered By: LukeFitz

If you’re interested in creating a new dict without using intermediary storage: (this is faster, and in my opinion, cleaner than using dict.items())

dic2 = dict(dic0, **dic1)

Or if you’re happy to use one of the existing dicts:

dic0.update(dic1)
Answered By: bluepnume

Here are quite a few ways to add dictionaries.

You can use Python3’s dictionary unpacking feature:

ndic = {**dic0, **dic1}

Note that in the case of duplicates, values from later arguments are used. This is also the case for the other examples listed here.


Or create a new dict by adding both items.

ndic = dict(tuple(dic0.items()) + tuple(dic1.items()))

If modifying dic0 is OK:

dic0.update(dic1)

If modifying dic0 is NOT OK:

ndic = dic0.copy()
ndic.update(dic1)

If all the keys in one dict are ensured to be strings (dic1 in this case, of course args can be swapped)

ndic = dict(dic0, **dic1)

In some cases it may be handy to use dict comprehensions (Python 2.7 or newer),
Especially if you want to filter out or transform some keys/values at the same time.

ndic = {k: v for d in (dic0, dic1) for k, v in d.items()}
Answered By: ideasman42
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.