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. Let’s see different methods to do the same.
Using == operator to Compare Two Dictionaries
Here we are using the equality comparison operator in Python to compare two dictionaries whether both have the same key value pairs or not.
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
Using Loop to Compare Two Dictionaries
Here we are checking the equality of two dictionaries by iterating through one of the dictionaries keys using for loop and checking for the same keys in the other dictionaries.
Python3
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
The time complexity of this code is O(n), where n is the number of key-value pairs in the dictionaries.
The auxiliary space complexity of this code is O(1), since the space used by the program does not depend on the size of the input.
Using List Comprehension to Compare Two Dictionaries
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.
Python3
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
Using DeepDiff module to Compare Two Dictionaries
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}}}