Merge Two Dictionaries in Python
In Python, dictionaries can be merged using various methods. Below are two examples that demonstrate different ways to combine two dictionaries.
Example 1: Using update()
Method
The update()
method merges two dictionaries, where the second dictionary is updated with the contents of the first.
# Function to merge two dictionaries using update() def Merge(dict1, dict2): return dict2.update(dict1) # Define two dictionaries dict1 = {'a': 10, 'b': 8} dict2 = {'d': 6, 'c': 4} # Print the result of the merge (None is returned since update() modifies in place) print(Merge(dict1, dict2)) # After merging, dict2 contains the values from both dictionaries print(dict2)
Output:
None {'d': 6, 'c': 4, 'a': 10, 'b': 8}
In this example, dict2
is updated with the key-value pairs from dict1
. The update()
method does not return a new dictionary, which is why the result of the Merge
function is None
. The merged dictionary is stored in dict2
.
Example 2: Using **
Operator
The **
operator can be used to merge two dictionaries by unpacking the key-value pairs from both into a new dictionary.
# Function to merge two dictionaries using the ** operator def Merge(dict1, dict2): res = {**dict1, **dict2} return res # Define two dictionaries dict1 = {'a': 10, 'b': 8} dict2 = {'d': 6, 'c': 4} # Merge the dictionaries and store the result in dict3 dict3 = Merge(dict1, dict2) print(dict3)
Output:
{'a': 10, 'b': 8, 'd': 6, 'c': 4}
In this method, the **
operator unpacks both dictionaries into a new dictionary, combining their contents.
Both methods are useful for merging dictionaries, but the **
operator is more suitable when you want to create a new dictionary, while update()
modifies an existing dictionary in place.