Compare Two Dictionaries in Python

Compare two dictionaries by finding common keys, unique keys, and value differences using Python's set operations.

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

Python code

24 lines
Python 3.9+
def compare_data(dict1, dict2):
    """Compare two dictionaries and summarize similarities/differences."""
    keys1 = set(dict1.keys())
    keys2 = set(dict2.keys())
    
    common_keys = keys1 & keys2
    only_in_first = keys1 - keys2
    only_in_second = keys2 - keys1
    
    print(f"Common keys ({len(common_keys)}): {sorted(common_keys)}")
    print(f"Keys only in first dict ({len(only_in_first)}): {sorted(only_in_first)}")
    print(f"Keys only in second dict ({len(only_in_second)}): {sorted(only_in_second)}")
    
    for key in sorted(common_keys):
        if dict1[key] == dict2[key]:
            print(f"  {key}: values match ({dict1[key]})")
        else:
            print(f"  {key}: DIFFER - first={dict1[key]!r}, second={dict2[key]!r}")


if __name__ == "__main__":
    user1 = {"name": "Alice", "age": 30, "city": "Paris", "hobby": "chess"}
    user2 = {"name": "Alice", "age": 31, "city": "Paris", "job": "engineer"}
    compare_data(user1, user2)

Output

stdout
Common keys (3): ['age', 'city', 'name']
Keys only in first dict (1): ['hobby']
Keys only in second dict (1): ['job']
  age: DIFFER - first=30, second=31
  city: values match (Paris)
  name: values match (Alice)

How it works

The function converts the keys of each dictionary into sets, which allows efficient set operations like intersection (&), difference (-), and symmetric difference. By iterating over sorted common keys, the output is deterministic and easy to read. For each common key, it compares values and prints whether they match or differ, using repr() to clearly show the values. This approach is O(n) for set creation and O(m log m) for sorting, making it efficient for most dictionary sizes.

Common mistakes

  • Forgetting that set operations return unordered sets, so sorting is needed for a stable output.
  • Comparing dictionaries directly with == which ignores key-only differences in reporting.
  • Assuming dict.keys() returns a list instead of a view that supports set operations.

Variations

  1. Return a dictionary of results instead of printing them for easier programmatic use.
  2. Use the symmetric difference operator ^ to find keys that are in only one dictionary.

Real-world use cases

  • Comparing config dictionaries between environments to spot mismatched settings.
  • Merging user profiles from two sources and identifying fields that need reconciliation.
  • Testing API responses against expected payloads to see which fields differ.

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.