Dictionary in python is a collection of key-value pairs. It is the same as an array instead the value here will be accessed by using the keys mapped. Whereas in arrays we use indexes.
Values in the dictionary can be of any type and they can be modified during the runtime. Whereas the type of keys are immutable and cannot be modified during runtime.
Merging dictionaries become easy in the latest versions of python. Let’s see how to do it in multiple versions of python >3.9, >3.5, >2, or <2
Python 3.9 or higher
# Creating a Dictionary1
Dict1= {1: 'Paper', 2: 'bun', 3:'is'}
# Creating a Dictionary2
Dict2= {4: 'the', 5:'best', 6:'place'}
# Merging the Dict1 and Dict2
Dict3 = Dict1 | Dict2
print(Dict3)
Python 3.5 or higher
# Creating a Dictionary1
Dict1= {1: 'Paper', 2: 'bun', 3:'is'}
# Creating a Dictionary2
Dict2= {4: 'the', 5:'best', 6:'place'}
# Merging the Dict1 and Dict2
Dict3 = {**Dict1 , **Dict2}
print(Dict3)
Python < 2 or higher
# Creating a Dictionary1
Dict1= {1: 'Paper', 2: 'bun', 3:'is'}
# Creating a Dictionary2
Dict2= {4: 'the', 5:'best', 6:'place'}
def merge_dicts(x, y):
z = x.copy()
z.update(y)
return z
Dict3 = merge_two_dicts(Dict1, Dict2)
print(Dict3)
Leave a Comment