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.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 14 views 0 copies

Python code

16 lines
Python 3.9+
def 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

stdout
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

  1. Use the merge operator {**dict1, **dict2} for a one-line dict merge in Python 3.9+
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.