How to Diff Two Dicts in Python: Added, Removed, and Changed Keys

Compare two dictionaries and report added, removed, and changed keys using Python's set operations on dict keys.

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

Python code

20 lines
Python 3.9+
def diff_dicts(old: dict, new: dict) -> dict:
    """Compare two dicts and report added, removed, and changed keys."""
    added = {k: new[k] for k in new.keys() - old.keys()}
    removed = {k: old[k] for k in old.keys() - new.keys()}

    common_keys = old.keys() & new.keys()
    changed = {k: (old[k], new[k]) for k in common_keys if old[k] != new[k]}

    return {"added": added, "removed": removed, "changed": changed}


if __name__ == "__main__":
    old_dict = {"a": 1, "b": 2, "c": 3, "d": 4}
    new_dict = {"b": 2, "c": 30, "d": 4, "e": 5}

    result = diff_dicts(old_dict, new_dict)

    print("Added keys:", result["added"])
    print("Removed keys:", result["removed"])
    print("Changed keys:", result["changed"])

Output

stdout
Added keys: {'e': 5}
Removed keys: {'a': 1}
Changed keys: {'c': (3, 30)}

How it works

This works because dict keys support set operations: - gives keys in one dict but not the other, and & gives common keys. The function builds new dicts from those key sets, pulling values from the appropriate source. For changed keys, it compares values on the intersection and stores the old and new value as a tuple. Because it's pure Python stdlib, it works on any dict size without extra dependencies.

Common mistakes

  • Using `old.items() - new.items()` which compares key-value pairs, not just keys
  • Forgetting that set operations treat dict_keys as immutable sets, so you can't modify them in place
  • Not handling nested dicts — this only does a shallow comparison

Variations

  1. Use `old.keys() ^ new.keys()` to get all keys that are not common, then separate them by checking membership
  2. For deep diffing, use the `deepdiff` library which handles nested structures

Real-world use cases

  • Comparing database records before and after an update to log which fields changed for audit trails.
  • Detecting configuration drift by diffing environment or app config dicts across deploys.
  • Merging user profile changes in a sync process to identify what needs to be re-uploaded.

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.