# Python >= 3.5: def merge_dictionaries(a, b): return {**a, **b} # else: def merge_dictionaries(a, b): c = a.copy() # make a copy of a c.update(b) # modify keys and values of a with the b ones return c a = { 'x': 1, 'y': 2} b = { 'y': 3, 'z': 4} print(merge_dictionaries(a, b)) # {'y': 3, 'x': 1, 'z': 4}
Here is what the above code is Doing:
1. The ** is the unpacking operator. It’s used to unpack a dictionary into keyword arguments.
2. The {**a, **b} is a dictionary comprehension. It’s a way to construct a dictionary from other dictionaries.
3. The {**a, **b} is equivalent to {‘x’: 1, ‘y’: 2, ‘y’: 3, ‘z’: 4}.
4. The {**a, **b} is equivalent to {‘x’: 1, ‘y’: 3, ‘z’: 4}.
5. The {**a, **b} is equivalent to {‘x’: 1, ‘y’: 3, ‘z’: 4}.