Merging or concatenating two dictionaries in Python can be achieved using several methods, depending on the Python version.
Methods:
1. Using the update() Method (Python 3.x):
python
dict1 = {‘a’: 1, ‘b’: 2}
dict2 = {‘c’: 3, ‘d’: 4}
dict1.update(dict2)
print(dict1) # {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
2. *Using the * Operator** (Python 3.5+):
python
merged_dict = {**dict1, **dict2}
print(merged_dict) # {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
3. Using the dict() Constructor (Python 3.9+):
python
merged_dict = dict(dict1, **dict2)
print(merged_dict) # {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
4. Using the | Operator (Python 3.9+):
python
merged_dict = dict1 | dict2
print(merged_dict) # {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
These methods efficiently combine two dictionaries, with later entries overwriting duplicates from earlier ones