Open In App

Python | Common items among dictionaries

Last Updated : 16 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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. 

Python3




# 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)))


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. 

Python3




# 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)))


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 #3: Using the & operator
Another approach to finding the common items among dictionaries is to use the & operator. The & operator compares the keys of the two dictionaries and returns the keys that are present in both dictionaries.

Python3




# Python3 code to demonstrate working of
# Equal items among dictionaries
# Using the & operator
 
# 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 the & operator
common_keys = set(test_dict1.keys()) & set(test_dict2.keys())
 
# printing result
print("The common items are : " + str(len(common_keys)))
#This code is contributed by Edula Vinay Kumar Reddy


Output

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

Time complexity: O(n)

Auxiliary Space: O(n), where n is number of items in both dictionaries.

Method 4 :  use a loop and compare the keys of both dictionaries. 

Two dictionaries, test_dict1 and test_dict2, are initialized with some key-value pairs.
The original dictionaries are printed using the print() function and string concatenation.
An empty list, common_keys, is created to store the common keys between the two dictionaries.
A for loop is used to iterate through the keys of test_dict1.
For each key in test_dict1, the if statement checks if it also exists in test_dict2.
If the key exists in test_dict2, it is added to the common_keys list using the append() method.
After all the keys of test_dict1 have been checked, the len() function is used to find the number of common keys, which is then printed using the print() function and string concatenation.

Python3




# Python3 code to demonstrate working of
# Equal items among dictionaries
# Using a loop
 
# 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
common_keys = []
for key in test_dict1:
    if key in test_dict2:
        common_keys.append(key)
 
# printing result
print("The common items are : " + str(len(common_keys)))


Output

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

The time complexity of this method is O(n), where n is the number of keys in test_dict1. The auxiliary space required is O(k), where k is the number of common keys between the dictionaries.

METHOD 5:Using counter method.

APPROACH:

This program finds the number of common items between two dictionaries using the Counter method of the collections module in Python. It converts the input dictionaries into Counter objects and calculates the intersection of the two counters to find the common items. Finally, it returns the count of common items.

ALGORITHM:

1. Define the input dictionaries.
2. Create Counter objects from the dictionaries using the Counter() function of the collections module.
3. Calculate the intersection of the two counters using the & operator.
4. Convert the resulting counter back into a dictionary.
5. Get the count of common items in the resulting dictionary.
6. Print the result.

Python3




import collections
 
# define the input dictionaries
dict1 = {'gfg': 1, 'best': 3, 'is': 2}
dict2 = {'gfg': 1, 'is': 2, 'good': 3}
 
# create Counter objects from the dictionaries
counter1 = collections.Counter(dict1)
counter2 = collections.Counter(dict2)
 
# calculate the intersection of the counters
common_items = dict(counter1 & counter2)
 
# print the result
print("The original dictionary 1 is:", dict1)
print("The original dictionary 2 is:", dict2)
print("The number of common items are:", len(common_items))


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

Time Complexity:
The time complexity of this program is O(n), where n is the total number of items in both dictionaries. This is because the Counter() function has a time complexity of O(n), and finding the intersection of the counters also takes O(n) time.

Space Complexity:
The space complexity of this program is O(m), where m is the total number of distinct items in both dictionaries. This is because the Counter() function creates a dictionary-like object that stores the count of each item, and the resulting dictionary only stores the common items. Therefore, the space used by the program is proportional to the number of distinct items, rather than the total number of items.



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
Python - Find the Common Keys from two Dictionaries
In this article, we will learn how can we print common keys from two Python dictionaries. We will see that there are multiple methods one can do this task. From brute force solutions of nested loops to optimize ones that trade between space and time to decrease the time complexity we will see different methods to do the task at hand and why they wo
4 min read
Python Program to find the profit or loss when CP of N items is equal to SP of M items
Given [Tex]N   [/Tex]and [Tex]M   [/Tex]denoting that the Cost Price of N articles is equal to the Selling Price of M articles. The task is to determine the profit or Loss percentage. Examples:  Input: N = 8, M = 9 Output: Loss = -11.11% Input: N = 8, M = 5 Output: Profit = 60% Formula:-  Below is the implementation of the above approach: C/C++ Cod
1 min read
Python | Common words among tuple strings
Sometimes, while working with tuples, we can have a problem in which we need to find the intersection of words that occur in strings inside single tuple with string as its elements. Let's discuss certain ways in which this problem can be solved. Method #1 : Using join() + set() + & operator + split() The combination of above functions can be us
4 min read
Python - Common items Dictionary Value List
The functionality of union has been discussed many times. But sometimes, we can have a more complex container, in which we need to check for the intersection of lists which are in form of keys of dictionary. Let’s discuss certain ways to solve this type of problem. Method #1: Using Loops Using loops is a naive brute force approach to perform this p
10 min read
Get the items which are not common of two Pandas series
Pandas does not support specific methods to perform set operations. However, we can use the following formula to get unique items from both the sets : [Tex] A \cup B - (A \cap B) [/Tex] Algorithm : Import the Pandas and NumPy modules. Create 2 Pandas Series. Find the union of the series using the union1d() method. Find the intersection of the serie
1 min read
Python | Sort Python Dictionaries by Key or Value
There are two elements in a Python dictionary-keys and values. You can sort the dictionary by keys, values, or both. In this article, we will discuss the methods of sorting dictionaries by key or value using Python. Need for Sorting Dictionary in PythonWe need sorting of data to reduce the complexity of the data and make queries faster and more eff
5 min read
Filter List of Python Dictionaries by Key in Python
Filtering a list of dictionaries in Python based on a specific key is a common task in data manipulation and analysis. Whether you're working with datasets or dictionaries, the ability to extract relevant information efficiently is crucial. In this article, we will explore some simple and commonly used methods to filter a list of dictionaries in Py
3 min read
Practice Tags :