Python Forum

Full Version: dict+dict
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
if abc and xyz are dictionaries, i can do abc.update(xyz) and have a combined dictionary as a result. but i sometimes don't want to modify either source dictionary. it would be nice if + could do this for me, like abc+xyz.
You can use the unpacking operator ** to do the job.

abc = {'abc': 123}
xyz = {'xyz': 456}
pdq = {**abc, **xyz}
print (pdq)
Output:
{'abc': 123, 'xyz': 456}
One rarely needs to mutate anything ;).

Another option is to use toolz.dicttoolz.merge (https://toolz.readthedocs.io/en/latest/a...oolz.merge). There's a lot of good stuff in Toolz.
https://docs.python.org/3/library/stdtyp...types-dict Wrote:d | other
Create a new dictionary with the merged keys and values of d and other, which must both be dictionaries. The values of other take priority when d and other share keys.

New in version 3.9.
abc = {'abc': 123}
xyz = {'xyz': 456}
pdq = abc | xyz
print(abc)
print(xyz)
print(pdq)
Output:
{'abc': 123} {'xyz': 456} {'abc': 123, 'xyz': 456}
Sometimes it is important to retain key-value pairs which are first encountered. For that ChainMap can be used:

>>> from collections import ChainMap
>>> d = {'a': 1, 'b': 2}
>>> d_2 = {'a': 11, 'b':22}
>>> d | d_2                   # next key value overwrites previous    
{'a': 11, 'b': 22}
>>> dict(ChainMap(d, d_2))
{'a': 1, 'b': 2}              # first value retained
i'm still coding for 3.6 and d1|d2 does not work. but {**d1,**d2} does. thanks!