How to compare two dictionaries in Python

In this Python tutorial, we will understand how to check if two dictionaries are equal in Python. Here we will see how to compare dictionaries with one another and find if both are the same.

There are mainly 4 methods to check if two dictionaries are equal in Python. All 4 methods are listed and discussed below.

  1. Using == operator
  2. Using for loop
  3. Using list comprehension
  4. Using deepdiff

How to check if two dictionaries are equal in Python

Here we will discuss all 4 main methods to check if two dictionaries are equal in Python. And we start with the first basic method of using the == operator in Python.

Method 1: Check if two dictionaries are equal in Python using the == operator

One of the basic ways to compare two strings in Python is by using the == comparison operator in Python.

The == is a comparison operator in Python that we can use to check if two objects are equal or not in Python. Moreover, we can use this operator with Python Dictionary as well.

So, let us see an example of using the == operator with the dictionary.

# Define two dictionaries
user_info1 = {'name': 'John', 'age': 30, 'city': 'New York'}
user_info2 = {'name': 'John', 'age': 30, 'city': 'New York'}

# Checking if the dictionaries are equal using the == operator
if user_info1 == user_info2:
    print("Both dictionaries are equal")
else:
    print("Both dictionaries are not equal")

In the above example, we have defined two dictionaries with the same data. And then we are comparing both the dictionaries using == operator and if statement.

And as both dictionaries are the same, we will get the following result.

Output: Both dictionaries are equal

However, let us change the value of any key from any of the dictionaries and compare again.

# Change one of the values in user_info2
user_info2['age'] = 25

# Check if the dictionaries are still equal using the == operator
if user_info1 == user_info2:
    print("Both dictionaries are equal")
else:
    print("Both dictionaries are not equal")

Here we modified the value of age from the user_info2 dictionary. And this time, as the dictionaries are not equal, we will get the following result.

Output: Both dictionaries are not equal

Read: Python Dictionary Methods

Method 2: Check if two dictionaries are equal in Python using for loop

  • In this method, we will use the dict.items() method to fetch the key and value of a dictionary separately.
  • Next, we will use the for loop to iterate over each key-value pair and use the if-else statement to compare if key-value pairs are the same in both dictionaries.

Here is an example of this approach in Python.

# Define two dictionaries
user_info1 = {'name': 'Adam', 'age': 28, 'city': 'Chicago'}
user_info2 = {'name': 'Adam', 'age': 28, 'city': 'Chicago'}

# Compare the key-value pairs of the dictionaries using a for loop
def compare_dict(dict1, dict2):
    for key, value in dict1.items():
        if key in dict2 and dict2[key] == value:
            continue
        else:
            print("Both dictionaries are not equal")
            break
    else:
        print("Both dictionaries are equal")
        
# Calling the function to compare
compare_dict(user_info1, user_info2)

In the above example, first, we defined two dictionaries, then we defined a function that will accept 2 dictionaries.

This function will use for loop with dict.items() method to iterate over each key-value pair. And within the loop, it uses the if statement to compare both keys and values.

In the last, the function returns a statement based on the dictionary comparison.

Output: Both dictionaries are equal

Now, let us change the value from one dictionary and compare both dictionaries again in Python.

# Change one of the values in user_info2
user_info2['age'] = 32

# Comparing again
compare_dict(user_info1, user_info2)

Here is the result once the change value from the 2nd dictionary.

Output: Both dictionaries are not equal

Read: Python dictionary extend

Method 3: Check if two dictionaries are equal in Python using list comprehension

  • In this method, we will use the list comprehension method to fetch each key and value from both dictionaries.
  • After this, we are comparing values to check if both dictionaries are the same. This will result in forming a list of boolean values.
  • Now, to check if all the values in the list are TRUE, we will use the all() function on the boolean list. And based on this, we will conclude if both dictionaries are the same.

Here is an example of this approach in Python.

# Define two dictionaries
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.")

# Calling function for compare dictionaries
compare_dict(job_counts1, job_counts2)

In the above code, we are comparing two same dictionaries in Python. So, after execution, we will get the following result.

Output: The job counts are equal.

Let us test our function by changing certain values and comparing both dictionaries again.

# Change one of the values in job_counts2
job_counts2['Los Angeles'] = 1300

# Calling function for compare dictionaries
compare_dict(job_counts1, job_counts2)

Now, as both dictionaries are not the same, we will get the following result in Python.

Output: The job counts are not equal.

Read: Python Dictionary Copy

Method 4: Check if two dictionaries are equal in Python using deepdiff

The deepdiff is a powerful library that helps to compare two Python objects and check if both objects are the same or not. This library also allows us to find the difference between both objects in Python.

However, to use this library first, we need to install this library in Python. For this, we will use the following command first.

pip install deepdiff

Once we have installed this library successfully, we can follow the given example.

# Importing DeepDiff
from deepdiff import DeepDiff

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

# Defining a function
def compare_dict(dict1, dict2):
    # Check if the two dictionaries are equal using deepdiff
    diff = DeepDiff(dict1, dict2, ignore_order=True)
    
    if not diff:
        print("Both dictionaries are equal.")
    else:
        print("Both dictionaries are not equal.")
        
# Calling function to compare dictionaries
compare_dict(job_counts1, job_counts2)

In this example, we have defined a function named compare_dict() which will accept 2 dictionary values. And this function will use the DeepDiff class to compare both dictionaries and return a result based on it.

So, once we call the function and pass two same dictionaries to it, we will get the following result.

Check if two dictionaries are equal in Python
Checking if two dictionaries are equal in Python

Additionally, we can also test this function by passing two different dictionaries to it.

# Change one of the values in job_counts2
job_counts2['Los Angeles'] = 1500

# Calling function to compare dictionaries
compare_dict(job_counts1, job_counts2)

Here we modified the value for one dictionary and compared them using the compare_dict() function.

The result for the above execution is given below.

Output: Both dictionaries are not equal.

You may also like to read the following Python tutorials.

Conclusion

So, in this Python tutorial, we understood how to check if two dictionaries are equal in Python or not. And for this implementation in Python, we covered 4 different methods. These 4 methods are listed below.

  • Using == operator
  • Using for loop
  • Using list comprehension
  • Using deepdiff