Find common elements in three sorted arrays by dictionary intersection in Python

While manipulating data using python we may come across situation where we need to find the elements which are common among the multiple arrays. This can be achieved by converting the arrayd into dictionaries as shown below.

In the below example we take the arrays and apply the Counter container from collections module. It will hold the count of each of the elements present in the container. Then we convert them to a dictionary by applying dict() and using the & operator to identify only the common elements among the arrays. Finally we loop through the items of the newly created dictionary and append the values from the dictionary to get the final result of common values.

Example

from collections import Counter

arrayA = ['Sun', 12, 14, 11, 34]
arrayB = [6, 12, 'Sun', 11]
arrayC = [19, 6, 20, 'Sun', 12, 67, 11]

arrayA = Counter(arrayA)
arrayB = Counter(arrayB)
arrayC = Counter(arrayC)

# Intersection
commonDict = dict(arrayA.items() & arrayB.items() & arrayC.items())
res = []

# result
for (key, val) in commonDict.items():
for i in range(0, val):
res.append(key)

print("The common values among the arrays are:\n ",res)

Output

Running the above code gives us the following result −

The common values among the arrays are:
['Sun', 11, 12]

Updated on: 26-Aug-2020

161 Views