Open In App

How to Compare Two Dictionaries in Python

Last Updated : 25 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will discuss how to compare two dictionaries in Python. The simplest way to compare two dictionaries for equality is by using the == operator.

Using == operator

This operator checks if both dictionaries have the same keys and values.

Python
d1 = {'a': 1, 'b': 2}
d2 = {'a': 1, 'b': 2}
d3 = {'a': 1, 'b': 3}

print(d1 == d2) 
print(d1 == d3) 

Output
True
False

Explanation:

  • d1 == d2 evaluates to True because both have identical key-value pairs.
  • d1 == d3 evaluates to False because the values for key 'b' differ.

Using Loop

Here we are checking the equality of two dictionaries by iterating through one of the dictionary keys using for loop and checking for the same keys in the other dictionaries.

Python
d1 = {'a': 1, 'b': 2}
d2 = {'a': 1, 'b': 2}

# Check if lengths are the same
if len(d1) != len(d2):
    print(False)
else:
  
    # Compare each key and value
    for key in d1:
        if key not in d2 or d1[key] != d2[key]:
            print(False)
            break
    else:
      
        # This runs only if no mismatches are found
        print(True)  

Output
True

Explanation:

  • Two dictionaries, d1 and d2, are defined with the same key-value pairs. The if statement checks if the lengths of the dictionaries are different. If they are, it prints False.
  • A for loop iterates through each key in d1 to check. If the key is missing in d2 or if the corresponding values differ, it prints False and stops the loop.
  • If no mismatches are found, the else block prints True, indicating the dictionaries are equal.

Related Articles:


Next Article

Similar Reads

  翻译: