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}
1def mergeDict(dict1, dict2):
2 ''' Merge dictionaries and keep values of common keys in list'''
3 dict3 = {**dict1, **dict2}
4 for key, value in dict3.items():
5 if key in dict1 and key in dict2:
6 dict3[key] = [value , dict1[key]]
7
8 return dict3
9
10# Merge dictionaries and add values of common keys in a list
11dict3 = mergeDict(dict1, dict2)
12
13print('Dictionary 3 :')
14print(dict3)
15