finding top k largest keys in a dictionary python

前端 未结 5 1037
自闭症患者
自闭症患者 2020-12-09 00:08

Lets say I have a dictionary:

{key1:value1........... keyn:valuen}

So lets say I want to write a function

def return_top_k(         


        
5条回答
  •  一整个雨季
    2020-12-09 00:35

    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.

提交回复
热议问题