
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Common Elements in Three Sorted Arrays Using 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]
Advertisements