finding top k largest keys in a dictionary python

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

    In code

    dct = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}
    k = 3
    print sorted(dct.keys(), reverse=True)[:k]
    

    If you also need values:

    print sorted(dct.items(), reverse=True)[:k]
    

    Or if you would want to use OrderedDict:

    from collections import OrderedDict
    d = OrderedDict(sorted(dct.items(), reverse=True))
    print d.keys()[:k]
    

提交回复
热议问题