Inverting a dictionary when some of the original values are identical

后端 未结 5 812
北海茫月
北海茫月 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:52

    Here's a version that doesn't "invert" the dictionary:

    >>> import operator
    >>> A = {'a':10, 'b':843, 'c': 39, 'd': 10}
    >>> B = sorted(A.iteritems(), key=operator.itemgetter(1), reverse=True)
    >>> B
    [('b', 843), ('c', 39), ('a', 10), ('d', 10)]
    

    Instead, it creates a list that is sorted, highest to lowest, by value.

    To get the top 25, you simply slice it: B[:25].

    And here's one way to get the keys and values separated (after putting them into a list of tuples):

    >>> [x[0] for x in B]
    ['b', 'c', 'a', 'd']
    >>> [x[1] for x in B]
    [843, 39, 10, 10]
    

    or

    >>> C, D = zip(*B)
    >>> C
    ('b', 'c', 'a', 'd')
    >>> D
    (843, 39, 10, 10)
    

    Note that if you only want to extract the keys or the values (and not both) you should have done so earlier. This is just examples of how to handle the tuple list.

提交回复
热议问题