Python ProgrammingPython Programming

Different ways to merge two dictionaries

##
# Python's program to merge two dictionaries.


d1 = {'a': 10, 'b': 20}
d2 = {'c': 30, 'd': 40, 'b': 50}

# Option 1
d1.update(d2)
print(d1)

d2.update(d1)
print(d2)

# Option 2
k = dict(list(d1.items()) + list(d2.items()))
print(k)

# Option 3
l = d1.copy()
l.update(d2)
print(l)

# Option 4
m = dict(d1, **d2)
print(m)

# Option 5
n = {**d1, **d2}
print(n)


Sample output of above program.
C:\programs\examples>pep8 --first example.py

C:\programs\examples>python example.py
{'a': 10, 'b': 50, 'c': 30, 'd': 40}
{'b': 50, 'd': 40, 'a': 10, 'c': 30}
{'a': 10, 'b': 50, 'c': 30, 'd': 40}
{'d': 40, 'c': 30, 'b': 50, 'a': 10}
{'d': 40, 'c': 30, 'b': 50, 'a': 10}
{'d': 40, 'c': 30, 'b': 50, 'a': 10}

C:\programs\examples>