Use min for one, nsmallest for a few, and sorted once k is a large share of the input
Four ways to get the k smallest, timed on a million random floats:
Predict
On a million floats, which is fastest for the single smallest, k = 1?
Method
k = 1
k = 1,000
k = 100,000
sort all, take k
135.2 ms
134.0 ms
136.6 ms
heapq.nsmallest
5.8 ms
10.6 ms
216.2 ms
k_smallest, a size-k heap
27.2 ms
36.4 ms
127.9 ms
heapify a copy, pop k
23.4 ms
24.6 ms
83.4 ms
Best of 3 to 5 runs each. min(d) took 5.8 ms for k = 1, the same as nsmallest, which calls it.
Peak memory for k = 10, from tracemalloc, Python's memory tracer: 11.44 MiB to sort, 7.63 MiB for the heapified copy, 1,112 bytes for k_smallest and 380 bytes for nsmallest.
Sorting costs the same for every k. The heaps get slower as k grows, until at k = 100,000 nsmallest is the slowest of the four. The heapq docs say the same: these functions do best for smaller values of n, and for larger ones sorted() is more efficient. Their n is this lesson's k.
The rule:
min or max for one item.
nsmallest or nlargest for a few.
sorted over nsmallest once k is a sizable share of the input. At k = 100,000, heapifying a copy and popping k beat both, if you can afford the copy.
Your own heap of size k when the items arrive one at a time and you need the answer as they come.
nlargest and nsmallest take a key, the way sorted does: heapq.nlargest(k, items, key=f) ranks each item by f(item).
In the editor, sizes maps file names to sizes in MB. Write largest_files(sizes, k): the k largest files as (name, size) pairs, largest first, with heapq.nlargest.
Pick an answer above to see the rest
Instructions
1
Write largest_files(sizes, k): the k largest files as (name, size) pairs, largest first.
2
Use heapq.nlargest on sizes.items(), with a key that ranks each pair by its size.