Check If Two Dictionaries Are Equal in Python

Checking the equality of two dictionaries allows you to determine if they have the same key-value pairs. In this blog post, we will explore different methods to check if two dictionaries are equal in Python.

Method 1: Using the == operator

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 2, "a": 1}

if dict1 == dict2:
    print("Dictionaries are equal")
else:
    print("Dictionaries are not equal")

Output:

Dictionaries are equal

Method 2: Using the cmp() function (for Python 2.x)

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 2, "a": 1}

if cmp(dict1, dict2) == 0:
    print("Dictionaries are equal")
else:
    print("Dictionaries are not equal")

Output:

Dictionaries are equal