finding top k largest keys in a dictionary python

前端 未结 5 1042
自闭症患者
自闭症患者 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:15

    O(n log k):

    import heapq
    
    k_keys_sorted = heapq.nlargest(k, dictionary)
    

    You could use key keyword parameter to specify what should be used as a sorting key e.g.:

    k_keys_sorted_by_values = heapq.nlargest(k, dictionary, key=dictionary.get)
    

提交回复
热议问题