Union of dictionaries python

dictionary, python, set

Solution

dict2.update(dict1)

This keeps all values from `dict1` (it overwrites the same keys in `dict2` if they exist).

Problem

I have two dictionaries that I want the union of so that each value from the first dictionary is kept and all the key:value pairs from the second dictionary is added to the new dictionary, without overriding the old entries. ``` dict1 = {'1': 1, '2': 1, '3': 1, '4': 1} dict2 = {'1': 3, '5': 0, '6': 0, '7': 0} ``` where the function `dictUnion(dict1, dict2)` returns ``` {'1': 1, '2': 1, '3': 1, '4': 1, '5': 0, '6': 0, '7': 0} ``` I can, and have done it by using simple loops, this is pretty slow though when operating on large dictionaries. A faster more "pythonic" way would be appreciated

Original source

Related problems