Inverting a dictionary when some of the original values are identical

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

    A defaultdict is perfect for this

    word_counter_dictionary = {'first':1, 'second':2, 'third':3, 'fourth':2}
    from collections import defaultdict
    
    d = defaultdict(list)
    for key, value in word_counter_dictionary.iteritems():
        d[value].append(key)
    
    print(d)
    

    Output:

    defaultdict(, {1: ['first'], 2: ['second', 'fourth'], 3: ['third']})
    

提交回复
热议问题