π Day 73/150 – Merge Two Dictionaries in Python
Dictionaries are one of Python’s most useful data structures, and combining two dictionaries is a common task when working with data.
In this post, we'll explore different ways to merge dictionaries in Python.
✅ Method 1 – Using update()
The update() method adds all key-value pairs from one dictionary into another.
dict1 = {"name": "John", "age": 20} dict2 = {"course": "Python", "city": "Delhi"} dict1.update(dict2) print(dict1)
Output
{'name': 'John', 'age': 20, 'course': 'Python', 'city': 'Delhi'}How it works
- update() modifies the original dictionary.
- Existing keys are overwritten if duplicates exist.
✅ Method 2 – Using Dictionary Unpacking (**)
Python allows unpacking dictionaries and combining them into a new dictionary.
{'name': 'John', 'age': 20, 'course': 'Python', 'city': 'Delhi'}dict1 = {"name": "John", "age": 20} dict2 = {"course": "Python", "city": "Delhi"} result = {**dict1, **dict2} print(result)
Output
Why use it?
- Creates a new dictionary.
- Keeps the original dictionaries unchanged.
✅ Method 3 – Using the | Operator (Python 3.9+)
Python 3.9 introduced a dedicated merge operator for dictionaries.
dict1 = {"name": "John", "age": 20} dict2 = {"course": "Python", "city": "Delhi"} result = dict1 | dict2 print(result)
Output
{'name': 'John', 'age': 20, 'course': 'Python', 'city': 'Delhi'}Benefits
- Clean and readable syntax.
- Returns a new merged dictionary.
✅ Method 4 – User-Defined Dictionaries
You can merge any dictionaries created by the user.
{'a': 1, 'b': 2, 'c': 3, 'd': 4}dict1 = {"a": 1, "b": 2} dict2 = {"c": 3, "d": 4} merged = {**dict1, **dict2} print(merged)
Output
⚠️ What Happens with Duplicate Keys?
dict1 = {"name": "John", "age": 20}dict2 = {"age": 25, "city": "Delhi"}result = {**dict1, **dict2}
print(result)
Output
{'name': 'John', 'age': 25, 'city': 'Delhi'}
The value from the second dictionary replaces the value from the first dictionary when keys are the same.
π― Key Takeaways
✔️ Use update() when you want to modify the existing dictionary.
✔️ Use ** unpacking when you want a new merged dictionary.
✔️ Use | operator for cleaner syntax in Python 3.9+.
✔️ If duplicate keys exist, the last dictionary's value wins.


0 Comments:
Post a Comment