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.
Python code
20 linesdef 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
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
- Use `old.keys() ^ new.keys()` to get all keys that are not common, then separate them by checking membership
- 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
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.