How to Compare Two Dictionaries in Python?
Last Updated :
27 Sep, 2024
In this article, we will discuss how to compare two dictionaries in Python. As we all know what is a dictionary, but sometimes we may need to compare two dictionaries.
Example: Best Way to Compare Two Dictionaries in Python
Python
dict1 = {'Name': 'asif', 'Age': 5}
dict2 = {'Name': 'lalita', 'Age': 78}
if dict1 == dict2:
print "dict1 is equal to dict2"
else:
print "dict1 is not equal to dict2"
Output:
dict1 is not equal to dict2
Explanation: Here we are using the equality comparison operator in Python to compare two dictionaries whether both have the same key value pairs or not.
Let’s see different methods to do the same.
Python Program to Compare Dictionary Using Loop
Here we are checking the equality of two dictionaries by iterating through one of the dictionary keys using for loop and checking for the same keys in the other dictionaries.
Python
dict1 = {'Name': 'asif', 'Age': 5}
dict2 = {'Name': 'asif', 'Age': 5}
if len(dict1)!=len(dict2):
print("Not equal")
else:
flag=0
for i in dict1:
if dict1.get(i)!=dict2.get(i):
flag=1
break
if flag==0:
print("Equal")
else:
print("Not equal")
Output:
Equal
Compare Two Dictionaries using List Comprehension
Here we are using the concept of list comprehension to compare the two dictionaries and checking whether the same key value pairs exists in the dictionary or not.
Python
d = {"a": 3, "b": 2}
d1 = {"a": 2, "b": 3}
res = all((d1.get(k) == v for k, v in d.items()))
print(res)
Output:
False
Compare Two Dictionaries using DeepDiff Module
This module is used to find the deep differences in dictionaries, iterables, strings, and other objects. To install this module type the below command in the terminal.
pip install deepdiff
Python
from deepdiff import DeepDiff
a = {'Name': 'asif', 'Age': 5}
b = {'Name': 'lalita', 'Age': 78}
diff = DeepDiff(a, b)
print(diff)
Output:
{'values_changed': {"root['Name']": {'new_value': 'lalita', 'old_value': 'asif'}, "root['Age']": {'new_value': 78, 'old_value': 5}}}