dict1 = {"a": 1, "b": 2, "c": 4}
dict2 = {"a": 1, "b": 2, "c": 3}
if dict1 == dict2:
print("The dictionaries are equal")
else:
print("The dictionaries are not equal")
Output
The dictionaries are not equal
The simplest technique to check if two or multiple dictionaries are equal is by using the == operator in Python. You can create the dictionaries with any of the methods defined in Python and then compare them using the == operator. It will return True the dictionaries are equals and False if not.
Syntax
dict1 == dict2 == dict3
Code example
dict1 = dict(a=1, b=2, c=3)
dict2 = dict(zip(['a', 'b', 'c'], [1, 2, 3]))
dict3 = dict([('b', 2), ('a', 1), ('c', 3)])
dict4 = dict({'b': 2, 'a': 1, 'c': 3})
# compare all dictionaries
if dict1 == dict2 == dict3 == dict4:
print('The dictionaries are equal')
# compare two dictionaries
if dict2 == dict4:
print('The dictionaries are equal')
Output
The dictionaries are equal
The dictionaries are equal
Explanation of the above code example
You can install the Python module deepdiff in your project and check the differences between the two dictionaries. We can install the deepdiff module using the below command in your project.
pip install deepdiff
We will be using the DeepDiff() function from the deepdiff module to compare the dictionaries. It will return the dictionary that will contain the information of the difference between the dictionaries.
Syntax
DeepDiff(dict1, dict2)
from deepdiff import DeepDiff
dict1 = {'a': 1, 'b': 2, 'c': 4}
dict2 = {'a': 1, 'c': 3, 'd': 5}
result = DeepDiff(dict1, dict2)
print(result)
Output
{'dictionary_item_added': [root['d']], 'dictionary_item_removed': [root['b']], 'values_changed': {"root['c']": {'new_value': 3, 'old_value': 4}}}
We can get the common key-value pairs from two dictionaries and check if those are equal or not. We will be using Python For loop to the common key-value pairs.
dict1 = {"a": 1, "b": 2, "c": 3}
dict2 = {"a": 3, "b": 2, "c": 3, "d": 4}
common = {}
for key in dict1:
if ((key in dict2) and (dict1[key] == dict2[key])):
common[key] = dict1[key]
# print common key-value pairs
print(common)
Output
{'b': 2, 'c': 3}
0 Comments