Skip to content
Related Articles

Related Articles

Python | Common items among dictionaries
  • Last Updated : 26 Aug, 2019

Sometimes, while working with Python, we can come across a problem in which we need to check for the equal items count among two dictionaries. This has an application in cases of web development and other domains as well. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using dictionary comprehension
This particular task can be performed in one line using dictionary comprehension which offers a way of compacting lengthy brute logic and just checks for equal items and increments count.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate the working of
# Equal items among dictionaries
# Using dictionary comprehension
  
# initializing dictionaries
test_dict1 = {'gfg' : 1, 'is' : 2, 'best' : 3}
test_dict2 = {'gfg' : 1, 'is' : 2, 'good' : 3}
  
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
  
# Equal items among dictionaries
# Using dictionary comprehension
res =  {key: test_dict1[key] for key in test_dict1 if 
        key in test_dict2 and test_dict1[key] == test_dict2[key]}
  
# printing result
print("The number of common items are : " + str(len(res)))

chevron_right


Output :

The original dictionary 1 is : {'gfg': 1, 'best': 3, 'is': 2}
The original dictionary 2 is : {'gfg': 1, 'is': 2, 'good': 3}
The number of common items are : 2

 

Method #2 : Using set() + XOR operator + items()
The combination of above methods can be used to perform this particular task. In this, the set function removes duplicates and XOR operator computes the matched items.



filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Equal items among dictionaries
# Using set() + XOR operator + items()
  
# initializing dictionaries
test_dict1 = {'gfg' : 1, 'is' : 2, 'best' : 3}
test_dict2 = {'gfg' : 1, 'is' : 2, 'good' : 3}
  
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
  
# Equal items among dictionaries
# Using set() + XOR operator + items()
res = set(test_dict1.items()) ^ set(test_dict2.items())
  
# printing result
print("The number of common items are : " + str(len(res)))

chevron_right


Output :

The original dictionary 1 is : {'gfg': 1, 'best': 3, 'is': 2}
The original dictionary 2 is : {'gfg': 1, 'is': 2, 'good': 3}
The number of common items are : 2

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :