Inverting a dictionary when some of the original values are identical

后端 未结 5 854
北海茫月
北海茫月 2021-01-19 23:57

Say I have a dictionary called word_counter_dictionary that counts how many words are in the document in the form {\'word\' : number}. For example,

5条回答
  •  遇见更好的自我
    2021-01-20 00:41

    For getting the largest elements of some dataset an inverted dictionary might not be the best data structure.

    Either put the items in a sorted list (example assumes you want to get to two most frequent words):

    word_counter_dictionary = {'first':1, 'second':2, 'third':3, 'fourth':2}
    counter_word_list = sorted((count, word) for word, count in word_counter_dictionary.items())
    

    Result:

    >>> print(counter_word_list[-2:])
    [(2, 'second'), (3, 'third')]
    

    Or use Python's included batteries (heapq.nlargest in this case):

    import heapq, operator
    print(heapq.nlargest(2, word_counter_dictionary.items(), key=operator.itemgetter(1)))
    

    Result:

    [('third', 3), ('second', 2)]
    

提交回复
热议问题