![]() |
Merging dictionaries in Python is a common operation. In this article, we will see how we can append two dictionaries so that they don’t overwrite each other in Python. Append two dictionaries so they don’t Overwrite Each OtherBelow are some of the ways by which we can append two dictionaries in Python:
Append Two Dictionaries Using the
|
# Sample dictionaries dict1 = { 'a' : 1 , 'b' : 2 } dict2 = { 'b' : 3 , 'c' : 4 } # Using update() method merged_dict = dict1.copy() merged_dict.update(dict2) print (merged_dict) |
{'a': 1, 'b': 3, 'c': 4}
**
Unpacking OperatorIn this example, two dictionaries, dict1
and dict2
, are provided. The ** unpacking operator is utilized to merge their contents into a new dictionary named merged_dict
. This concise approach combines the key-value pairs from both dictionaries, and if there are overlapping keys, the values from dict2
will overwrite the values from dict1
. The final merged dictionary is then printed.
# Sample dictionaries dict1 = { 'a' : 1 , 'b' : 2 } dict2 = { 'b' : 3 , 'c' : 4 } # Using ** unpacking operator merged_dict = { * * dict1, * * dict2} print (merged_dict) |
{'a': 1, 'b': 3, 'c': 4}
collections.ChainMap
ClassIn this example, the collections
module’s ChainMap
is utilized to merge two dictionaries, dict1
and dict2
. The ChainMap
class efficiently combines the dictionaries, creating a view that allows access to the keys and values from both dictionaries as if they were a single dictionary. The resulting merged_dict
is then converted into a regular dictionary using dict()
, and the combined key-value pairs are printed.
from collections import ChainMap # Sample dictionaries dict1 = { 'a' : 1 , 'e' : 2 } dict2 = { 'b' : 3 , 'c' : 4 } # Using ChainMap merged_dict = dict (ChainMap(dict1, dict2)) print (merged_dict) |
{'b': 3, 'c': 4, 'a': 1, 'e': 2}
dict()
Constructor and UnpackingIn this example, the dict()
constructor and the ** unpacking operator are employed to merge two dictionaries, dict1
and dict2
. The resulting merged_dict
contains the combined key-value pairs from both dictionaries. If there are overlapping keys, the values from dict2
will overwrite the values from dict1
.
# Sample dictionaries dict1 = { 'a' : 1 , 'b' : 2 } dict2 = { 'b' : 3 , 'c' : 4 } # Using dict() constructor and unpacking merged_dict = dict (dict1, * * dict2) print (merged_dict) |
{'a': 1, 'b': 3, 'c': 4}
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |