Finding Commonalities in Two Dictionaries In Python

In this tutorial, we have two dictionaries and want to find out what they might have in common (like the same keys, same values, etc.). Basically there are some similarities between the two dictionaries and you have to find out these similarities then this article is most helpful. SO let’s start learning how to compare two dictionaries in Python and find similarities between them.

Similarities between dictionaries in Python

Basically A dictionary is a mapping between a set of keys and values. The keys support the basic operations like unions, intersections, and differences. When we call the items() method on a dictionary then it simply returns the (key, value) pair.

Now, Consider two dictionaries:

a = {   'x' : 1,   'y' : 2,   'z' : 3 }
b = {   'w' : 10,   'x' : 11,   'y' : 2 }

Find keys in common of two dictionaries in Python

Here, we write a code that finds the keys that are common in two dictionary as:

a = {   'x' : 1,   'y' : 2,   'z' : 3 }
b = {   'w' : 10,   'x' : 11,   'y' : 2 } 
common_keys = a.keys() & b.keys() # intersection operation on keys
print("The common keys are :",common_keys)

Output :

The common keys are : {'x', 'y'}

Find keys in a dictionary A that are not in dictionary B

Now , we are finding that keys which are present in dictionary a and not in dictionary b as:

A = {   'x' : 1,   'y' : 2,   'z' : 3 }
B = {   'w' : 10,   'x' : 11,   'y' : 2 } 
diffrent_keys = A.keys() - B.keys()   
print("The key that are in A and not in B are :",diffrent_keys)

Output :

The key that are in A and not in B are : {'z'}

Find (key,value) pairs in common in dictionaries in Python

Now, we perform the an operation by which we are finding the (key,value) pair that is common in both dictionary as:

a = {   'x' : 1,   'y' : 2,   'z' : 3 }
b = {   'w' : 10,   'x' : 11,   'y' : 2 }
common_key_value_pairs  = a.items() & b.items()   
print("The common (key,value) pairs are :",common_key_value_pairs)

Output :

The common (key,value) pairs are : {('y', 2)}

For more information about dictionary you can also refer the following links :

Sum of values of elements in a Dictionary in Python

Sort A Dictionary By Key In Python

How to merge two dictionary in Python

Leave a Reply

Your email address will not be published. Required fields are marked *