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 top K frequent elements from a list of tuples in Python
We have a list of tuples. In it we are required to find the top k frequent element. If k is 3 we are required to find the top three elements from the tuples inside the list.
With defaultdict
We put the the elements into a dictionary container using defaultdict. Then find out only the elements which satisfy that top k conditions.
Example
import collections
from operator import itemgetter
from itertools import chain
# Input list initialization
listA = [[('Mon', 126)], [('Tue', 768)],[('Wed', 512)], [('Thu', 13)],[('Fri', 341)]]
# set K
K = 3
#Given list
print("Given list:\n",listA)
print("Check value:\n",K)
# Using defaultdict
dict_ = collections.defaultdict(list)
new_list = list(chain.from_iterable(listA))
for elem in new_list:
dict_[elem[0]].append(elem[1])
res = {k: sum(v) for k, v in dict_.items()}
# Using sorted
res = sorted(res.items(), key=itemgetter(1),
reverse=True)[0:K]
# Output
print("Top 3 elements are:\n", res)
Output
Running the above code gives us the following result −
Given list:
[[('Mon', 126)], [('Tue', 768)], [('Wed', 512)], [('Thu', 13)], [('Fri', 341)]]
Check value:
3
Top 3 elements are:
[('Tue', 768), ('Wed', 512), ('Fri', 341)]
With sorted and itergetter
In this approach we use the itemgetter function but apply it within the sorted function by mentioning the range from 0 to K.
Example
from operator import itemgetter
from itertools import chain
# Input list initialization
listA = [[('Mon', 126)], [('Tue', 768)],[('Wed', 512)], [('Thu', 13)],[('Fri', 341)]]
# set K
K = 3
#Given list
print("Given list:\n",listA)
print("Check value:\n",K)
# Using sorted
res = sorted(list(chain.from_iterable(listA)),
key = itemgetter(1), reverse = True)[0:K]
# Output
print("Top 3 elements are:\n", res)
Output
Running the above code gives us the following result −
Given list:
[[('Mon', 126)], [('Tue', 768)], [('Wed', 512)], [('Thu', 13)], [('Fri', 341)]]
Check value:
3
Top 3 elements are:
[('Tue', 768), ('Wed', 512), ('Fri', 341)]Advertisements