How to Merge Dictionaries and Find Unique Keys in Python
Merge two dictionaries with update(), then use sets to find all unique keys and the keys shared between both dictionaries.
Python code
16 linesdef merge_and_unique(dict1, dict2):
merged = dict1.copy()
merged.update(dict2)
unique_keys = set(merged.keys())
common_keys = set(dict1.keys()) & set(dict2.keys())
return merged, unique_keys, common_keys
if __name__ == "__main__":
fruits = {"apple": 3, "banana": 5, "orange": 2}
more_fruits = {"banana": 7, "grape": 4, "kiwi": 1}
result = merge_and_unique(fruits, more_fruits)
print("Merged dictionary:", result[0])
print("Unique keys:", result[1])
print("Common keys:", result[2])
Output
Merged dictionary: {'apple': 3, 'banana': 7, 'orange': 2, 'grape': 4, 'kiwi': 1}
Unique keys: {'grape', 'kiwi', 'banana', 'orange', 'apple'}
Common keys: {'banana'}
How it works
The dict.copy() call creates a shallow copy of the first dictionary so the original isn't mutated. merged.update(dict2) overlays the second dictionary's key-value pairs onto the copy, so later values win for duplicate keys. Converting merged.keys() to a set gives all unique key names across both dictionaries. The & operator on two sets returns a set of keys present in both original dictionaries. This combination of dict and set operations gives you a clean three-part result: merged data, unique keys, and overlapping keys.
Common mistakes
- Mutating the original dict by calling update() directly instead of copying first
- Assuming update() merges values for duplicate keys instead of overwriting them
- Forgetting that set iteration order is not guaranteed, so printed order may vary
Variations
- Use the merge operator {**dict1, **dict2} for a one-line dict merge in Python 3.9+
- Use dict1.keys() & dict2.keys() instead of converting to sets, since dict_keys supports set operations directly
Real-world use cases
- Merging configuration defaults with user overrides where later values should win.
- Comparing two API response payloads to identify fields added, changed, or shared between versions.
- Combining inventory updates from multiple sources and detecting which product IDs appear in both.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.