How to Check If Two Dictionaries Are Equal in Python

Introduction

Python Dictionary is the built-in data type that acts as the container for the key-value pairs. To check whether two dictionaries are equal or not will be using two methods:
1. Python Equality operator(==)
2. DeepDiff library

Dictionary is a robust type of data type that is mutable in nature. It supports different data types like integer, string, float, list, tuple, set, boolean, and nested dictionary.

We can also create the dictionary in different ways as:

dict_1 = dict(a="Apple", b="Bat", c="Cat") # using dict object
dict_2 = {"a": "Apple", "b":"Bat", "c":"Cat"} # without dict object
dict_3 = dict([("a", "Apple"), ("b", "Bat"), ("c", "Cat")]) # wrapping tuples of list in dict object
dict_4 = dict({"a": "Apple", "b": "Bat", "c": "Cat"}) # wrapping dictionary itself in dict object

Python dictionary creation methods

 

Methods to Check Two Dictionaries Equality

While working with dictionaries in Python, in some cases we have to check whether the two dictionaries’ objects are equal or not as we cannot check manually just by eye-sighting.

Checking two dictionaries using the Equality(==) operator

The equality (==) operator is very much handy and one of the useful operators that can be used to compare two objects. It returns a boolean value either True or False.

Let’s create a function named “check_dictionary_equality” that checks whether the two dictionaries’ key-value pairs are equal or not using the == operator. It returns the output as “Dictionaries are equal” or “Dictionaries are not equal” based on the comparison.

def check_dictionary_equality(dict1, dict2):
    """Check If Two Dictionaries Are Equal"""
    if dict1 == dict2:
        print("Dictionaries are equal")
    else:
        print("Dictionaries are not equal")

In the below example, we call the “check_dictionary_equality” function in different scenarios.

a. Check on the same order key-value pairs

dict_1 = {
    'C': 'Dennis Ritchie',
    'JavaScript': 'Brendan Eich',
    'Python': 'Guido van Rossum',
    'Java': 'James Gosling'
}

dict_2 = dict(
    C='Dennis Ritchie',
    JavaScript='Brendan Eich',
    Python='Guido van Rossum',
    Java='James Gosling'
)

dict_3 = {
    'C': 'Dennis Ritchie',
    'C++': 'Bjarne Stroustrup',
    'Python': 'Guido van Rossum',
    'Java': 'James Gosling'
}


# Check on the same order
check_dictionary_equality(dict_1, dict_2)
check_dictionary_equality(dict_1, dict_3)

Output

Dictionaries are equal
Dictionaries are not equal

 

b. Check on different order key-value pairs

dict_1 = {
    'C': 'Dennis Ritchie',
    'JavaScript': 'Brendan Eich',
    'Python': 'Guido van Rossum',
    'Java': 'James Gosling'
}

dict_2 = dict(
    Java='James Gosling',
    JavaScript='Brendan Eich',
    Python='Guido van Rossum',
    C='Dennis Ritchie'
)


# Check on different order
check_dictionary_equality(dict_1, dict_2)

Output

Dictionaries are equal

check if two dictionaries are equal python

 

c. Check on the list or tuple as a values

dict_1 = dict(
    name="Python Dictionary",
    type="Python data type",
    version=("v1.0", "v2.0", "v3.0"),  # tuple immutable
    supports=["string", "integer", "list", "set"],  # list mutable
    is_active=True
)

dict_2 = {
    "name": "Python Dictionary",
    "is_active": True,
    "type": "Python data type",
    "version": ("v1.0", "v2.0", "v3.0"),
    "supports": ["string", "integer", "list", "set"]
}

# Check on the list or tuple as values for key
check_dictionary_equality(dict_1, dict_2)
check_dictionary_equality(dict_1, {"name": "Python"})

Output

Dictionaries are equal
Dictionaries are not equal

 

d. Check on the nested dictionaries

dict_1 = {
    'one': 1,
    'two': 2,
    'vowels': {
        "a": "A",
        "e": "E",
        "i": "I",
        "o": "O",
        "u": "U"
    },
}

dict_2 = dict(
    two=2,
    one=1,
    vowels=dict(
        a="A",
        e="E",
        i="I",
        o="O",
        u="U"
    )
)

dict_3 = {
    'one': 1,
    'two': 2,
    'vowels': {
        "a": "A",
        "i": "I",
        "o": "O",
        "u": "U"
    },
}


# Check on the nested dictionaries
check_dictionary_equality(dict_1, dict_2)
check_dictionary_equality(dict_1, dict_3)

Output

Dictionaries are equal
Dictionaries are not equal

 

Extracting common key-value pairs from dictionaries

While solving problems in Python, there can come scenarios where you want to extract common pairs from two existing dictionary objects.

For that, we have to use for loop for iterating through the shortest dictionary. And the equality operator(==) that we used above in order to check whether the key values are equal or not.

Also, we need an empty dictionary to store the common pairs.

dict_1 = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6}

dict_2 = {"nine": 9, "nineteen": 19, "two": 2,
          "eight": 8, "three": 3, "twenty": 20, "fifty": 50}

# create empty dict for storing common pairs
common_pairs = {}

for key in dict_1:
    if key in dict_2 and dict_1[key] == dict_2[key]:
        common_pairs.update({key: dict_1[key]})

# print the common key-value in dict_1 & dict_2
print(common_pairs)

Output

{'two': 2, 'three': 3}

 

Checking using the DeepDiff library

The DeepDiff is the Python third-party library that gives us the deep difference of any Python object.

It includes the following modules:

DeepDiff: For the Deep Difference between two Python objects like iterables, strings, etc.

DeepSearch: Uses for searching objects within other objects.

DeepHash: This module basically hash any object based on its content even if they are not “hashable” in Python’s eyes.

Delta: It’s the delta of objects that can be applied to other objects.

Extract: This module is used for extracting a path from an object.

Commandline: This module is the command line version of the above modules.

Wait for a second, we don’t need to have knowledge of all the modules. For now, just have a brief insight so that you can use it later on.

We will just focus on the DeepDiff module now:-)

To install this library type the below command in the terminal.

pip install deepdiff

 

Example 1:

from deepdiff import DeepDiff


dict_1 = {"Name": "Shiv", "Profession": "Doctor", "Age": 50}
dict_2 = {"Name": "Rajesh", "Profession": "Doctor", "Age": 50}
dict_3 = {"Age": 50, "Name": "Shiv", "Profession": "Doctor"}

diff_1 = DeepDiff(dict_1, dict_2)
diff_2 = DeepDiff(dict_1, dict_3)

print(diff_1)
print(diff_2)

Output

{'values_changed': {"root['Name']": {'new_value': 'Rajesh', 'old_value': 'Shiv'}}}
{}

Here in the first diff, I change the key of “Name” to “Rajesh”. There is the output you can see that the value was changed from “Shiv” to “Rajesh”.

Similarly in the second diff, I just tweak the order and pass it to the DeepDiff() function, output returns as empty {} which depicts no differences right there means they are equal dictionary objects.

 

Example 2: 

Ignoring the case of values during the comparison

from deepdiff import DeepDiff


dict_1 = {"Name": "Shiv", "Profession": "Doctor", "Age": 50}
dict_2 = {"Age": 50, "Name": "shiv", "Profession": "doctor"}

# ignore string case while checking objects
diff = DeepDiff(dict_1, dict_2, ignore_string_case=True)

print(diff)

Output

{}

Here in the above code, although “Shiv” & “shiv” are treated as different objects in Python. By passing ignore_string_case=True inside the DeepDiff function dict_1 and dict_2 objects are treated as equal and return value as {}.

 

Conclusion

And There You Have It! Ways to Check If Two Dictionaries Are Equal in Python.

I Hope I’ve Shown You, all the methods that can be used to check two dictionaries are whether equal or not.

We started by creating dictionary objects using different methods and comparing those objects using the python built-in operator == and the third-party library DeepDiff.

We also extracted the common key-value pairs that exist in two dictionaries and utilize the useful functions provided by the DeepDiff module.

Have doubts about Python Dictionary Methods? Python Dictionary Methods with Examples

python-dictionary-methods-examples

 

References

DeepDiff

Check out other blogs:

Leave a Comment