In Python, you can merge two dictionaries into a single dictionary using the update
method or the **
operator.
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}
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}
Note that if the dictionaries have overlapping keys, the values in the second dictionary will overwrite the values in the first dictionary.