How to find the difference between two dictionaries in Python?

Published on Aug. 22, 2023, 12:17 p.m.

There are multiple approaches to find the difference between two dictionaries in Python:

  1. Using set operations: To find the keys that are missing in one dictionary compared to the other, you can use the difference between the set of keys of both dictionaries. Here is an example:
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'c': 3, 'd': 4}

missing_in_dict1 = set(dict2.keys()) - set(dict1.keys())
missing_in_dict2 = set(dict1.keys()) - set(dict2.keys())
different_values = {k: (dict1[k], dict2[k]) for k in dict1 if k in dict2 and dict1[k] != dict2[k]}

print(missing_in_dict1) # {'d'}
print(missing_in_dict2) # {'b'}
print(different_values) # {'c': (3, 4)}
  1. Using dictionary comprehension: You could subtract one dictionary from another to get a dictionary containing only the key-value pairs that are different. Here is an example code snippet:
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'c': 4, 'd': 5}

difference_dict = {k: dict2[k] for k in set(dict2) - set(dict1)}

print(difference_dict) # {'c': 4, 'd': 5}
  1. Using a third-party library: You could use a third-party library like deepdiff or dictdiffer to find the difference between two dictionaries. Here is an example using deepdiff:
from deepdiff import DeepDiff

dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'c': 4, 'd': 5}

diff = DeepDiff(dict1, dict2)
print(diff) # {'dictionary_item_added': {'root.d'}}

These methods can be used to find the difference between two dictionaries based on your requirements.

Tags: