Q:

How to compare two dictionaries in Python?

0

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

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

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now