Lets say I have a dictionary:
{key1:value1........... keyn:valuen}
So lets say I want to write a function
def return_top_k(
return sorted(dictionary, key=dictionary.get, reverse=True)[:10]
Should be at worst O(NlogN)
(although heapq
proposed by others is probably better) ...
It might also make sense to use a Counter
instead of a regular dictionary. In that case, the most_common
method will do (approximately) what you want (dictionary.most_common(10)
), but only if it makes sense to use a Counter
in your API.