Merging or Concatenating two Dictionaries in Python
Combining two dictionaries is a common task when working with Python, especially when we need to consolidate data from multiple sources or update existing records. For example, we may have one dictionary containing user information and another with additional details and we'd like to merge them into one. Let's explore different approaches to do this.
Using update()
update() method can be used to merge dictionaries. It modifies one dictionary by adding or updating key-value pairs from another.
d1 = {'x': 1, 'y': 2}
d2 = {'y': 3, 'z': 4}
d1.update(d2)
print(d1)
Output
{'x': 1, 'y': 3, 'z': 4}
Explanation:
- d1.update(d2) adds all key-value pairs from d2 to d1.
- If a key exists in both d1 and d2 (e.g., 'y'), the value from d2 (3) replaces the value in d1 (2).
Note: This method modifies the original dictionary (d1).
Lets explore other methods to merge or concatenate two dictionaries:
Using | Operator (Python 3.9+)
| operator introduced in Python 3.9 can be used to merge dictionaries. It creates a new dictionary without modifying the original dictionary.
d1 = {'x': 1, 'y': 2}
d2 = {'y': 3, 'z': 4}
d3 = d1 | d2
print(d3)
Output:
{'x': 1, 'y': 3, 'z': 4}
Explanation:
- | operator combines d1 and d2 into d1 new dictionary d3.
- Duplicate keys are handled by keeping the value from the dictionary on the right (d2).
Using Dictionary Unpacking (**)
Dictionary unpacking allows us to merge dictionaries into a new one.
d1 = {'x': 1, 'y': 2}
d2 = {'y': 3, 'z': 4}
d3 = {**d1, **d2}
print(d3)
Output
{'x': 1, 'y': 3, 'z': 4}
Explanation:
- **d1 and **d2 unpack the key-value pairs of d1 and d2 into the new dictionary d3.
- Keys from d2 overwrite duplicates from d1.
Using Loop
We can use a loop (for loop) to merge dictionaries.
d1 = {'x': 1, 'y': 2}
d2 = {'y': 3, 'z': 4}
d3 = d1.copy()
for key, value in d2.items():
d3[key] = value
print(d3)
Output
{'x': 1, 'y': 3, 'z': 4}
Explanation:
- d1.copy() creates a shallow copy of d1 to preserve the original dictionary.
- for loop iterates through each key-value pair in d2 and adds or updates it in d3.