Merge Two Dictionaries In Python
Chapter:
Python
Last Updated:
24-05-2023 17:20:28 UTC
Program:
/* ............... START ............... */
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
dict1.update(dict2)
print(dict1)
## Alternatively, you can use the unpacking operator (**) to merge dictionaries:
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged_dict = {**dict1, **dict2}
print(merged_dict)
/* ............... END ............... */
Output
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Notes:
-
First Example, update() method is used to merge dict2 into dict1. The update() method adds all the key-value pairs from dict2 into dict1. If there are any common keys, the values from dict2 will overwrite the values in dict1.
- Alternatively, you can use the unpacking operator (**) to merge dictionaries:
- In second example, the unpacking operator is used to create a new dictionary merged_dict by unpacking the key-value pairs from dict1 and dict2.
- Both methods produce the same result, merging the contents of the two dictionaries into one.