easy +10 pts

Top k keys by count

Return the k most frequent keys from a dictionary, tied keys by alphabetical order.

Write a function `top_k_keys(data: dict, k: int) -> list` that takes a dictionary `data` where keys are strings and values are integers (counts). It should return a list of the `k` keys with the highest counts. If two keys have the same count, the one that comes first in alphabetical (lexicographic) order should appear first. If `k` is greater than the number of keys, return all keys (in the same order). If `k` is 0 or negative, return an empty list. The input dictionary is not empty unless stated otherwise; assume `data` is a valid dictionary.

Constraints

- `0 <= k <= 10^6` - Dictionary size `n` satisfies `0 <= n <= 10^5` - Keys are non-empty strings. - Values are integers. - Time: O(n log n) or better. Sorting is acceptable.

Example

```python
>>> top_k_keys({'a': 3, 'b': 1, 'c': 3}, 2)
['a', 'c']
>>> top_k_keys({'x': 1, 'y': 2}, 5)
['y', 'x']
>>> top_k_keys({'z': 0}, 0)
[]
```
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Sort the dictionary items by a custom key that combines count descending and key ascending.
Remember to handle k values larger than the dictionary size by slicing.
You can use the sorted() function with the key parameter: key=lambda item: (-item[1], item[0]).
If k <= 0, return [] immediately.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.