Open In App

How to Compare Two Dictionaries in Python?

Last Updated : 13 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to compare two dictionaries in Python. As we all know what is a dictionary, but sometimes we may need to compare two dictionaries. Let’s see different methods to do the same.

Using == operator to Compare Two Dictionaries

Here we are using the equality comparison operator in Python to compare two dictionaries whether both have the same key value pairs or not.

Python




dict1 = {'Name': 'asif', 'Age': 5}
dict2 = {'Name': 'lalita', 'Age': 78}
 
if dict1 == dict2:
    print "dict1 is equal to dict2"
else:
    print "dict1 is not equal to dict2"


Output:

dict1 is not equal to dict2

Using Loop to Compare Two Dictionaries

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

Python3




dict1 = {'Name': 'asif', 'Age': 5}
dict2 = {'Name': 'asif', 'Age': 5}
 
if len(dict1)!=len(dict2):
    print("Not equal")
     
else:
   
    flag=0
    for i in dict1:
        if dict1.get(i)!=dict2.get(i):
            flag=1
            break
    if flag==0:
        print("Equal")
    else:
        print("Not equal")


Output:

Equal

The time complexity of this code is O(n), where n is the number of key-value pairs in the dictionaries.

The auxiliary space complexity of this code is O(1), since the space used by the program does not depend on the size of the input.

Using List Comprehension to Compare Two Dictionaries

Here we are using the concept of list comprehension to compare the two dictionaries and checking whether the same key value pairs exists in the dictionary or not.

Python3




d = {"a": 3, "b": 2}
d1 = {"a": 2, "b": 3}
res = all((d1.get(k) == v for k, v in d.items()))
print(res)


Output:

False

Using DeepDiff module to Compare Two Dictionaries 

This module is used to find the deep differences in dictionaries, iterables, strings, and other objects. To install this module type the below command in the terminal.

pip install deepdiff

Python




from deepdiff import DeepDiff
 
a = {'Name': 'asif', 'Age': 5}
b = {'Name': 'lalita', 'Age': 78}
 
diff = DeepDiff(a, b)
 
print(diff)


Output:

{‘values_changed’: {“root[‘Name’]”: {‘new_value’: ‘lalita’, ‘old_value’: ‘asif’}, “root[‘Age’]”: {‘new_value’: 78, ‘old_value’: 5}}}



Previous Article
Next Article

Similar Reads

Python - Convert Dictionaries List to Order Key Nested dictionaries
Given list of dictionaries, convert to ordered key dictionary with each key contained dictionary as its nested value. Input : test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}] Output : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}} Explanation : List converted to dictionary with index keys. Input : test_list = [{"is": 8, "Good" : 2}] Output :
6 min read
Python Program to extract Dictionaries with given Key from a list of dictionaries
Given a list of dictionaries, the task is to write a python program that extracts only those dictionaries that contain a specific given key value. Input : test_list = [{'gfg' : 2, 'is' : 8, 'good' : 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3}], key= "gfg"Output : [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}] Expl
6 min read
Convert Dictionary of Dictionaries to Python List of Dictionaries
Dictionaries are powerful data structures in Python, allowing the storage of key-value pairs. Sometimes, we encounter scenarios where we have a dictionary of dictionaries, and we need to convert it into a list of dictionaries for easier manipulation or processing. In this article, we'll explore five different methods to achieve this conversion, eac
3 min read
Convert a List of Dictionaries into a Set of Dictionaries
Python's versatility allows developers to manipulate data in various ways. When working with a list of dictionaries, there might be scenarios where you want to convert it into a set of dictionaries to eliminate duplicates or for other reasons. In this article, we'll explore three different methods to achieve this goal with code examples. Convert A
3 min read
How To Compare Two Dataframes with Pandas compare?
A DataFrame is a 2D structure composed of rows and columns, and where data is stored into a tubular form. It is mutable in terms of size, and heterogeneous tabular data. Arithmetic operations can also be performed on both row and column labels. To know more about the creation of Pandas DataFrame. Here, we will see how to compare two DataFrames with
5 min read
Python - Compare Dictionaries on certain Keys
Sometimes, while working with Python dictionaries, we can have a problem in which we need to compare dictionaries for equality on bases in selected keys. This kind of problem is common and has application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop This is brute force way in which this task
5 min read
Python | Difference in keys of two dictionaries
In this article, we will be given two dictionaries dic1 and dic2 which may contain the same keys and we have to find the difference of keys in the given dictionaries using Python. Example Input: dict1= {'key1':'Geeks', 'key2':'For', 'key3':'geeks'}, dict2= {'key1':'Geeks', 'key2':'Portal'} Output: key3 Explanation: key1 and key2 is already present
5 min read
Python | Combine the values of two dictionaries having same key
Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. Combining dictionaries is very common task in operations of dictionary. Let's see how to combine the values
7 min read
Python | Intersect two dictionaries through keys
Given two dictionaries, the task is to find the intersection of these two dictionaries through keys. Let's see different ways to do this task. Method #1: Using dict comprehension C/C++ Code # Python code to demonstrate # intersection of two dictionaries # using dict comprehension # initialising dictionary ini_dict1 = {'nikhil': 1, 'vashu' : 5, 'man
4 min read
Python | Merging two list of dictionaries
Given two list of dictionaries, the task is to merge these two lists of dictionaries based on some value. Merging two list of dictionariesUsing defaultdict and extend to merge two list of dictionaries based on school_id. C/C++ Code # Python code to merge two list of dictionaries # based on some value. from collections import defaultdict # List init
6 min read
three90RightbarBannerImg