How to Check If Two Dictionaries are Equal in Python [4 ways]

In this Python tutorial, we will understand “How Python check if two dictionaries are equal or not” in some different ways or techniques with practical examples.

While working on a Python Project, I needed to check whether two dictionaries were equal before merging the data. So, I found multiple ways to help you compare two dictionaries in Python.

I thought this would help you when you need to validate data containing key-value pairs.

How to check if two dictionaries are equal in Python

Let’s understand the scenario with a straightforward example so you will know where to use all those methods.

There are two dictionaries like this:

employees_data = {1 : "James", 2 : "Peter", 3 : "George".........}
validate_emp_data = {1 : "James", 2 : "Peter", 3 : "George".....}

Now, I need to compare validate_emp_data with employees_data, so here, we can use all those approaches to get this type of output

Data Matched

There are 4 ways to check if two dictionaries are equal in Python. Let’s understand all those approaches one by one with some realistic examples.

Python Check If Two Dictionaries are Equal using the “==” operator

First, we will use a comparison operator,” ==”, which compares two values in Python and will return True or False based on the given condition.

So, we will use the operator “==” to compare two dictionaries in Python. It will check the keys and values of both dictionaries and if they are the same, they will return True; otherwise, they will return False.

READ:  Python Tkinter search box

Syntax

dict1 == dict2

Let’s understand how Python Checks Whether Two Dictionaries are Equal or not using the ” == ” operator.

employees_data = {'name': 'John', 'age': 30, 'city': 'New York'}
validate_emp_data = {'name': 'John', 'age': 30, 'city': 'New York'}

if employees_data == validate_emp_data:
    print("Both dictionaries are equal")
else:
    print("Both dictionaries are not equal")
Python Check If Two Dictionaries are Equal using == operator

In the above code, we have a dictionary of employees_data and validate_emp_data. I need to check whether both dictionary keys and values match.

So we use the == operator inside the if condition, such as “if employees_data == validate_emp_data:”, to check Python dict equality.

How to check if two dictionaries are equal Python using for loop

We can also use “for loop” to check both dicts are equal in Python. It will target and compare every key-value pair of both dictionaries one by one. Also, we’ve used the ” != ” operator to make a condition.

Let’s see an example to check Python dictionary equality using for loop

employees_data = {'name': 'John', 'age': 30, 'city': 'New York'}
validate_emp_data = {'name': 'John', 'age': 30, 'city': 'New York'}

# Here we are checking that length of both dictionaries are same or not
if len(employees_data) != len(validate_emp_data):
  print("The dictionaries are not equal.")
  exit()

for key in employees_data:
    try:
        if employees_data[key] != validate_emp_data[key]:
            print("The Dictionaries are not equal.")
            exit()
    except Exception as e:
        print("Dictionaries keys are not equal")
        exit()

print("The dictionaries are equal.")
How to check if two dictionaries are equal Python using for loop

In the above code, first, we check the length of both dictionaries like this: if len(employees_data) != len(validate_emp_data) because we are comparing the whole dictionary, and if the length is not equal, then it will print not matched and exit the program using exit() method in Python.

READ:  raw input function in Python

Then we initialize the for loop like this: “for key in employees_data” to iterate over every key one by one in sequence and compare two dict in Python.

Check if 2 dictionaries are equal in Python using list comprehension

Now, we will use list comprehension with all() methods in Python.

The all() method returns True if you give a parameter, which is an iterable collection. It uses list comprehension to iterate over every dictionary key and compare it with others.

job_counts1 = {'New York City': 1000, 'San Francisco': 800, 'Los Angeles': 1200}
job_counts2 = {'New York City': 1000, 'San Francisco': 800, 'Los Angeles': 1200}

# Check if the two dictionaries are equal using list comprehension
def compare_dict(dict1, dict2):
    equal = all([dict1[key] == dict2[key] for key in dict1.keys() if key in dict2])
    
    if equal:
        print("The job counts are equal.")
    else:
        print("The job counts are not equal.")

compare_dict(job_counts1, job_counts2)
check python dictionary equality using list comprehension

In the above code, we have two dictionaries named job_counts1 and job_counts2, and we need to compare both dicts to check their equality.

So, we are using list comprehension as a parameter of all() methods like this :
equal = all([dict1[key] == dict2[key] for key in dict1.keys() if key in dict2]). We are targeting keys with the help of dict.keys() method “for key in dict1.keys()“.

Then, check whether the key is in dict2, like this: “if key in dict2”. If yes, compare the values of both keys: “[dict1[key] == dict2[key]”. Based on that condition, it will return True or False.

How to compare two dictionaries in Python using DeepDiff()

The DeepDiff() method is a built-in method of the deepdiff module in Python. Before importing the module, you must install it separately to use its built-in methods.

pip install deepdiff

You can install the package using this command in your Windows terminal.

READ:  How to Find the Armstrong Number in Python using Recursion

In Python, DeepDiff() is a very useful tool because it will check the equality of both dictionaries directly.

If it matches, it will return empty brackets like” {} “; if it doesn’t match, it will return the values that are not matched and show the difference between both dictionaries.

Syntax

DeepDiff(dict1, dict2)

Let’s understand How Python Check If Two Dictionaries are Equal using the DeepDiff() method.

from deepdiff import DeepDiff

def compare_dicts(dict1, dict2):

  diff = DeepDiff(dict1, dict2)
  return diff.to_dict()

user_info1 = {'name': 'Adam', 'age': 28, 'city': 'Chicago'}
user_info2 = {'name': 'Adam', 'age': 29, 'city': 'Chicago'}

diff = compare_dicts(user_info1, user_info2)

if diff == {}:
  print("Dictionary matched")
else:
  print("Not matched")
  print(diff)
How to compare two dictionaries in Python using DeepDiff()

In the above code, we have two dictionaries named user_info1 and user_info2. We need to compare both; if they are not equal, I need to know the differences. That’s why we use the DeepDiff() method to get the exact data that does not match.

Let’s make changes in the previous dictionary and see the output.

how to check python dict equality using deepdif()

So, we changed the person’s age in user_info2, and now it will give output like this
{‘values_changed’: {“root[‘age’]”: {‘new_value’: 30, ‘old_value’: 28}}}“.

Conclusion

In this Python article, you learned How Python Check If Two Dictionaries are Equal or not with 4 different approaches using the “==” operator, for loop, list comprehension, and using the DeepDiff() method in Python.

You can use all these approaches when comparing two dictionaries in Python.

You may like to read: