← Back to Python, page 5

python-0089 · Medium mid

Use heapq to get the top k items and to merge already-sorted streams.

heapq implements a min-heap on a plain list: heappush and heappop are O(log n). nlargest and nsmallest return top k items in O(n log k), better than sorting when k is small. heapq.merge lazily merges sorted inputs, and a heap of (priority, counter, item) tuples gives a stable priority queue.

Full answer
python
import heapq, itertools

scores = {"asha": 91, "ben": 78, "chen": 88, "dev": 95, "esha": 67}
print(heapq.nlargest(3, scores.items(), key=lambda kv: kv[1]))

stream_a = [1, 4, 9]
stream_b = [2, 3, 10]
print(list(heapq.merge(stream_a, stream_b)))

queue, counter = [], itertools.count()
for priority, task in [(2, "email"), (1, "payment"), (2, "report"), (0, "outage")]:
    heapq.heappush(queue, (priority, next(counter), task))
print([heapq.heappop(queue)[2] for _ in range(len(queue))])

Output:

text
[('dev', 95), ('asha', 91), ('chen', 88)]
[1, 2, 3, 4, 9, 10]
['outage', 'payment', 'email', 'report']

nlargest returns the three highest scores without sorting all five. heapq.merge consumes the inputs lazily, so it can merge sorted files that do not fit in memory. In the priority queue, the counter breaks ties: 'email' and 'report' share priority 2 and come out in insertion order, and the task strings are never compared. heapq is a min-heap; for a max-heap, push negated priorities.

python
import heapq, itertools

scores = {"asha": 91, "ben": 78, "chen": 88, "dev": 95, "esha": 67}
print(heapq.nlargest(3, scores.items(), key=lambda kv: kv[1]))

stream_a = [1, 4, 9]
stream_b = [2, 3, 10]
print(list(heapq.merge(stream_a, stream_b)))

queue, counter = [], itertools.count()
for priority, task in [(2, "email"), (1, "payment"), (2, "report"), (0, "outage")]:
    heapq.heappush(queue, (priority, next(counter), task))
print([heapq.heappop(queue)[2] for _ in range(len(queue))])

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • heapq is a min-heap on a list
  • push and pop are O(log n)
  • nlargest for top k
  • merge for sorted streams
  • Counter tie-breaker for stable priorities

Common mistakes

  • Sorting everything to take the top 3
  • Heap entries that compare unorderable items on ties

Follow-ups

  • How would you find the median of a stream?
  • When would you use queue.PriorityQueue instead?

Tips

  • Mention the tie-breaker