k most frequent numbers

Write k_frequent(nums, k) that returns the k values that appear most often, most frequent first; when two values tie, the smaller comes first. k is at most the number of distinct values.

k_frequent([1, 1, 1, 2, 2, 3], 2)  ->  [1, 2]
k_frequent([4, 4, 5, 5, 6], 2)     ->  [4, 5]

The point is to practise a heap keyed on (-count, value).

def k_frequent(nums, k):
    ...