Check if Two Dictionaries Are Equal in Python

I was working on a project where I had to compare two large dictionaries in Python. These dictionaries contained employee records from different departments, and I needed to quickly check if they were the same.

At first, I thought it would be as simple as comparing two Python lists, but dictionaries are unordered collections, so it’s not always easy. Over the years, I’ve tried different approaches, and in this tutorial, I’ll share the most practical methods I’ve used.

I’ll cover four simple ways to check if two dictionaries are equal in Python. Each method has its own use case, and I’ll explain when I prefer one over the other.

Methods to Check if Two Dictionaries Are Equal in Python

Let’s understand the scenario with a simple 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 with examples.

Method 1: Use the “==” Operator in Python

I will use a comparison operator,” ==”, which compares the keys and values of both dictionaries, and if they are the same, it will return True; otherwise, it will return False.

Syntax

dict1 == dict2

code:

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")

You can refer to the screenshot below to see the output.

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.

Method 2: Use Python For Loop

We can also use a “for loop” to check if both dictionaries 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.

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.")

You can refer to the screenshot below to see the output.

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

We are comparing the whole dictionary, and if the length is not equal, then it will print not matched and exit the program using the exit() method in Python.

Method 3: Use List Comprehension in Python

The all() method returns True if you give a parameter, which is an iterable collection. It uses Python 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)

You can refer to the screenshot below to see the output.

check python dictionary equality using list comprehension

I used 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()”.

Method 4: Use DeepDiff() in Python

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.

In Python, DeepDiff() is a very useful tool because it checks 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 two dictionaries.

Syntax

DeepDiff(dict1, dict2)

code

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()

If both values are not equal, we 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}}}.

In this Python article, you learned how Python checks if Two Dictionaries are Equal or not with four 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:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.