Inverting a dictionary when some of the original values are identical

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

    What you can do is convert the value in a list of words with the same key:

    word_counter_dictionary = {'first':1, 'second':2, 'third':3, 'fourth':2}
    
    inverted_dictionary = {}
    for key in word_counter_dictionary:
        new_key = word_counter_dictionary[key]
        if new_key in inverted_dictionary:
            inverted_dictionary[new_key].append(str(key))
        else:
            inverted_dictionary[new_key] = [str(key)]
    
    print inverted_dictionary
    
    >>> {1: ['first'], 2: ['second', 'fourth'], 3: ['third']}
    

提交回复
热议问题