To merge two dictionaries in Python, you can use the update()
method or the **
operator.
Option 1: Using the update()
method:
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict1.update(dict2)
print(dict1)
Output:
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
In this method, the update()
method adds the key-value pairs from dict2
into dict1
. If there are any common keys, the corresponding values in dict1
will be updated with the values from dict2
.
Option 2: Using the **
operator:
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict)
Output:
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
In this method, the **
operator unpacks the key-value pairs from both dictionaries and creates a new dictionary with those pairs. If there are any common keys, the corresponding values from the second dictionary (dict2
) will overwrite the values from the first dictionary (dict1
).
Either method can be used to merge dictionaries in Python, choose the one that suits your needs and coding style.