How to compare two dictionaries in Python?

Here, we are going to learn how to compare two dictionaries in Python? Comparing two dictionaries using == operator and DeepDiff() method.
Submitted by Shivang Yadav, on March 18, 2021

Given three dictionaries record1, record2, and record3, we have to compare them.

To compare two dictionaries, we are using two methods here,

  1. Using == operator
  2. Using DeepDiff() method

1) Compare two dictionaries using == operator

Equal to (==) operator compares two dictionaries and returns True if both are dictionaries are equal, False otherwise.

# Python program to compare two dictionaries 
# using == operator

record1 = {'id': 101, 'name': 'Shivang Yadav', 'Age': 21} 
record2 = {'id': 101, 'name': 'Shivang Yadav', 'Age': 21} 
record3 = {'id': 102, 'name': 'Radib Kar', 'Age': 23} 

if record1 == record2: 
	print("record1 is equal to record2")
else: 
	print("record1 is not equal to record2")

if record2 == record3: 
	print("record2 is equal to record3")
else: 
	print("record2 is not equal to record3")

Output:

record1 is equal to record2
record2 is not equal to record3

2) Compare two dictionaries using DeepDiff() method

The DeepDiff() method is from "deepdiff" module and it compares the difference between two dictionaries (other collections also), and returns the changed values.

# Python program to compare two dictionaries 
# using DeepDiff() method

from deepdiff import DeepDiff

record1 = {'id': 101, 'name': 'Shivang Yadav', 'Age': 21} 
record2 = {'id': 101, 'name': 'Shivang Yadav', 'Age': 21} 
record3 = {'id': 102, 'name': 'Radib Kar', 'Age': 23} 

diff = DeepDiff(record1, record2) 

print("Diff. b/w record1 & record2")
print(diff)

diff = DeepDiff(record2, record3) 

print("Diff. b/w record2 & record3")
print(diff)

Output:

Diff. b/w record1 & record2
{}
Diff. b/w record2 & record3
{'values_changed': {"root['id']": {'new_value': 102, 'old_value': 101}, 
"root['name']": {'new_value': 'Radib Kar', 'old_value': 'Shivang Yadav'}, 
"root['Age']": {'new_value': 23, 'old_value': 21}}}

Note: You need to install the module "deepdiff" first.

Python Dictionary Programs »





Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.