1dict1 = {'color': 'blue', 'shape': 'square'}
2dict2 = {'color': 'red', 'edges': 4}
3
4dict1.update(dict2) #if a key exists in both, it takes the value of the second dict
5# dict1 = {'color': 'red', 'shape': 'square', 'edges': 4}
6# dict2 is left unchanged
1# Python >= 3.5:
2def merge_dictionaries(a, b):
3 return {**a, **b}
4
5# else:
6def merge_dictionaries(a, b):
7 c = a.copy() # make a copy of a
8 c.update(b) # modify keys and values of a with the b ones
9 return c
10
11a = { 'x': 1, 'y': 2}
12b = { 'y': 3, 'z': 4}
13print(merge_dictionaries(a, b)) # {'y': 3, 'x': 1, 'z': 4}
1>>> x = {'a': 1, 'b': 2}
2>>> y = {'b': 10, 'c': 11}
3>>> z = {**x, **y} #In Python 3.5 or greater only
4>>> print(z)
5{'a': 1, 'b': 10, 'c': 11}
6
1def merge_dicts(dict1, dict2):
2 """Here's an example of a for-loop being used abusively."""
3 return {**dict2, **{k: (v if not (k in dict2) else (v + dict2.get(k)) if isinstance(v, list) else merge_dicts(v, dict2.get(k))) if isinstance(v, dict) else v for k, v in dict1.items()}}