Python Merge Dictionaries
Given two dictionaries, then merge them into one dictionary.
Example 1: Using the update() method, the second argument is merged into the first
def
Merge
(
dict1
,
dict2
)
:
return
(
dict2
.
update
(
dict1
)
)
Two dictionaries
dict1
= {
'
a
'
:
10
,
'
b
'
:
8
}
dict2
= {
'
d
'
:
6
,
'
c
'
:
4
}
Returns None
(
Merge
(
dict1
,
dict2
)
)
dict2 has merged dict1
(
dict2
)
The output of the code above is:
None
{'d': 6, 'c': 4, 'a': 10, 'b': 8}
Example 2: Using **, the function imports arguments as a dictionary
def
Merge
(
dict1
,
dict2
)
:
res
= {**
dict1
, **
dict2
}
return
res
Two dictionaries
dict1
= {
'
a
'
:
10
,
'
b
'
:
8
}
dict2
= {
'
d
'
:
6
,
'
c
'
:
4
}
dict3
=
Merge
(
dict1
,
dict2
)
(
dict3
)
The output of the code above is:
{'a': 10, 'b': 8, 'd': 6, 'c': 4}
Python3 Examples