finding top k largest keys in a dictionary python

前端 未结 5 1036
自闭症患者
自闭症患者 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)
    
    0 讨论(0)
  • 2020-12-09 00:17
    portfolio = [
       {'name': 'IBM', 'shares': 100, 'price': 91.1},
       {'name': 'AAPL', 'shares': 50, 'price': 543.22},
       {'name': 'FB', 'shares': 200, 'price': 21.09},
       {'name': 'HPQ', 'shares': 35, 'price': 31.75},
       {'name': 'YHOO', 'shares': 45, 'price': 16.35},
       {'name': 'ACME', 'shares': 75, 'price': 115.65}
    ]
    
    cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
    expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
    
    0 讨论(0)
  • 2020-12-09 00:20

    For top-3 step by step:

    >>> from operator import itemgetter
    >>> dct = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}
    >>> sorted(dct.items(), key=itemgetter(1), reverse=True)
    [('e', 5), ('d', 4), ('c', 3), ('b', 2), ('a', 1)]
    >>> map(itemgetter(0), sorted(dct.items(), key=itemgetter(1), reverse=True))
    ['e', 'd', 'c', 'b', 'a']
    >>> map(itemgetter(0), sorted(dct.items(), key=itemgetter(1), reverse=True))[:3]
    ['e', 'd', 'c']
    

    Or using heapq module

    >>> import heapq
    >>> heapq.nlargest(3, dct.items(), key=itemgetter(1))
    [('e', 5), ('d', 4), ('c', 3)]
    >>> map(itemgetter(0), _)
    ['e', 'd', 'c']
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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]
    
    0 讨论(0)
提交回复
热议问题