Compare Two Dictionaries and Check if Key-Value Pairs are Equal

Compare Two Dictionaries

Python dictionary is a data structure for storing a group of objects. Dictionaries have a set of keys and each key has a single associated value. In simple words dictionary stores data in key-value pairs. A pair of braces creates an empty dictionary: {}.

As we know, Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Python is a high-level, general-purpose programming language.  It supports multiple programming paradigms, including structured, object-oriented, and functional programming.  The basic Python data structures in Python include lists, sets, tuples, and dictionaries. Data structures are a group of data according to type.

Before getting started, let’s check whether python is installed or not in the system.

Checking for Python in System

Even though Python is already installed in the system. To check if it’s installed, open cmd/terminal and type python – -version

python --version
Python Version 1
Python Version

If you get the version, then you are good to go. Else, you can refer here for the Python Installation. We need python in our system to run python codes.

What is a Dictionary?

As we learned above, the dictionary is a data structure like lists, tuples, and sets. A dictionary is used for storing data or a group of objects. Dictionary stores data in key-value pairs. A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key: value pairs within the braces adds initial key: value pairs to the dictionary; this is also the way dictionaries are written on output.

Syntax:

dict = { key: value, "key": value, "key": "value" ..... }

Let’s take a look at a simple example of a dictionary

Example:

dict = {"name": "Dhushi", "age": 6}
print(dict)
print(dict["name"])
print(dict["age"])
  1. we are assigning a simple dictionary to variable dict with “name” and “age” as the keys and “Dhushi” and “6” as the values of the keys.
  2. print the full dictionary
  3. printing the value of the “name” key
  4. printing the value of the “age” key

Result:

Dictionary Example
Dictionary Example

In the output, we are getting a full dictionary, the value of the name key, and the value of the age key.

Now let’s move on to the topic of how to do a comparison of two dictionaries.

You may also check: 4 Easy Techniques to Check if Key Exists in a Python Dictionary

Comparison Between Two Dictionaries

When we talk about comparison in the dictionary, we think about whether both dictionaries have the same key value pairs or not.

Example 1: By using the equal “==” Operator

Yes, it is that simple we can use equal “==” operator to check whether two dictionaries are the same or not. Now let’s see how we can use it.

Case 1:

dict1 = {'name': "Dhushi", 'hobbies': ['art', 'dance']}
dict2 = {'hobbies': ['art', 'dance'],'name': "Dhushi"}

if(dict1 == dict2):
    print ("Yes, dict1 and dict2 are same")
else:
    print("No, dict1 and dict2 are not same")
  • assigned two dictionaries in dict1 and dict2 with the same key value pairs but arranged in a different order.
  • use the if keyword to check whether dict1 “==” dict2. Here we used an equal operator, which will check whether they are the same or not.
  • if the condition is True then it will print “Yes, dict1 and dict2 are the same”.
  • else when the condition turns to False, then it will print “No, dict1 and dict2 are not same”.

Result:

Compare Two Dict
Compare Two Dictionary

In the output, we can see that the condition is True despite the changed order. As a result, it prints “Yes, dict1 and dict2 are the same”.

What if the values get changed, and dictionaries are not equal? Let’s code for that, also.

Case 2:

dict1 = {'name': "Dhushi", 'hobbies': ['art', 'dance']}
dict2 = {'hobbies': ['art', 'dance'],'name': "Lee"}

if(dict1 == dict2):
    print ("Yes, dict1 and dict2 are same")
else:
    print("No, dict1 and dict2 are not same")

In this piece of code, we just changed the value of the key name to “Lee.” The whole code is the same as above.

Result:

Compare Two Dict False
Compare Two Dict False

In this case, as we have changed the value of the key, the condition turns out to be False. so here the else block gets executed, which prints “No, dict1 and dict2 are not same”.

Example 2: By using List Comprehension

The other way to compare dictionaries is by using List Comprehension. List Comprehension is a shorter syntax where you can create a new list based on the values of an existing list.

dict1 = {"name": "Dhushi", "age": 6}
dict2 = {"name": "Dhushi", "age": 3}
result = all([dict2.get(key) == value for key, value in dict1.items()])
print(result)
  1. firstly, assigned to two dictionaries in variable dict1 and dict2
  2. changed the value of the key “age” to 3 from before.
  3. we are using list comprehension in line 3 where we are using the all() function which returns True if all items in an iterable are true, otherwise, it returns False.
  4. we are comparing the dict2 with the dict1 key and values

Note: The get() method returns the value of the specified key.

Result:

False

So, as we can look at the result all() return the bool value, which is False here. It means the dictionaries are not the same because we have changed the key “age” value.

Check if Key: Value Pairs are Equal in the Dictionaries

We learned above how to compare two dictionaries. Now, we are going to look at how to check if the key: value pairs are equal in the dictionaries. It is also like a comparison only but in a bit more depth. For the following, we need to install “deepdiff” package.

What is deepdiff?

deepdiff is a python package for deep difference and search of any Python object/data. As per the docs, it is used for Deep Differences in dictionaries, iterable, strings, and other objects. It will recursively look for all the changes.

Installation

pip install deepdiff

Like any other package, python uses the pip command to install the dependency.

Example:

from deepdiff import DeepDiff

a = {'Name': 'Dhushi', 'Age': 6}
b = {'Name': 'Praj', 'Age': 26, "language": "JavaScript"}

print(len(a)==len(b)) 
print(a==b) 

diff = DeepDiff( a, b)
 
print(diff)
  1. import DeepDiff from deepdiff so we can get the function DeepDiff which will help us find the difference between dictionaries, iterables, strings, and other objects. It will recursively look for all the changes.
  2. declared two different dictionaries of different lengths in the a and b variables
  3. firstly, we print whether the length of the two dictionaries are the same or not by using len() function
  4. Then we check, whether the two dictionaries are the same or not
  5. lastly, we are using DeepDiff() function for the comparison, and let’s look at the result down.

Result:

Deepdiff Dict Comparison
Deepdiff Dictionary Comparison

Let’s look at the result produced through the above code.

  • firstly, we are getting the value False because the lengths of dictionaries a and b are different, which is right because dictionary b has one additional key-value pair
  • secondly, we are getting the value False because obviously, the dictionaries are not the same, and as well they are not equal
  • lastly, the important part, we provided our two dictionaries to DeepdDiff() function where we are comparing dictionary b from a so the result produced over here is like that we have added an additional item or a new key-value pair which is the key[‘language’],
  • then we are getting the changed values in dictionary a, the name key’s value was Dhushi, but now it has changed to Praj in dictionary b, similarly with the key age

Conclusion

In this article, we saw how to do a comparison of two dictionaries by using the equal “==” operator, list comprehension, and using DeepDiff() function. The equal “==” operator is the straightforward and easy way to know if the two dictionaries are the same or not. List Comprehension is also a method where you can compare dictionaries. Lastly, the Deepdiff() provides the detailed result where you can see the freshly added values key and the changed values of the keys.