Use heaq.nlargest
:
import heapq
heapq.nlargest(2, list_of_t, key=lambda x:x[1])
Demo:
>>> import heapq
>>> list_of_t = [('a', 100), ('b', 5), ('c', 50)]
>>> heapq.nlargest(2, list_of_t, key=lambda x:x[1])
[('a', 100), ('c', 50)]
Question
I have a list of tuples with following format ("key","value"), I need to extract keys with highest & second highest values & store them, how do I achieve this in python ?
Solution
Use heaq.nlargest
:
import heapq
heapq.nlargest(2, list_of_t, key=lambda x:x[1])
Demo:
>>> import heapq
>>> list_of_t = [('a', 100), ('b', 5), ('c', 50)]
>>> heapq.nlargest(2, list_of_t, key=lambda x:x[1])
[('a', 100), ('c', 50)]
OTHER TIPS
Try this:
# initial data
tuples = [("First", 20), ("Second", 10), ("Third", 30)]
# sort by value and reverse it
sorted_tuples = sorted(tuples, key=lambda tuple: tuple[1])[::-1]
# show result
print(sorted_tuples[0])
print(sorted_tuples[1])
# results:
#
# ('Third', 30)
# ('First', 20)