How can two dictionaries be merged in Python?

In Python, you can merge two dictionaries using the update() method. This method adds the key-value pairs from the second dictionary to the first dictionary, and if there are any duplicate keys, the value from the second dictionary will overwrite the value in the first dictionary.

Here is an example code for merging two dictionaries:

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

dict1.update(dict2)

print(dict1)

The output result is:

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

In the code above, dict1 is the first dictionary and dict2 is the second dictionary. By calling the update() method and passing dict2 as a parameter, you can merge dict2 into dict1. Finally, use the print() function to print the merged dictionary.

bannerAds