Python Program - Merge Two Dictionaries
https://wfigi.wwtidea.com
To merge two dictionaries in Python, we can use the update()
method or the **
operator.
Here's an example program that demonstrates both methods:
# Merge two dictionaries using the update() method dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} merged_dict = dict1.copy() merged_dict.update(dict2) print("Merged dictionary using update() method:", merged_dict) # Merge two dictionaries using the ** operator dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} merged_dict = {**dict1, **dict2} print("Merged dictionary using ** operator:", merged_dict)
In this program, we have two dictionaries dict1
and dict2
.
To merge the dictionaries using the update()
method, we first make a copy of dict1
and then update it with the items from dict2
. The update()
method modifies the original dictionary in place.
To merge the dictionaries using the **
operator, we simply use the **
operator with the dictionaries. This creates a new dictionary that contains the items from both dictionaries.
The output of the program is:
Merged dictionary using update() method: {'a': 1, 'b': 2, 'c': 3, 'd': 4} Merged dictionary using ** operator: {'a': 1, 'b': 2, 'c': 3, 'd': 4}