How to reverse a dictionary that has repeated values

后端 未结 6 1814
抹茶落季
抹茶落季 2020-11-28 14:48

I have a dictionary with almost 100,000 (key, value) pairs and the majority of the keys map to the same values. For example:

mydict =  {\'a\': 1, \'c\': 2, \'         


        
6条回答
  •  一整个雨季
    2020-11-28 15:07

    Using collections.defaultdict:

    from collections import defaultdict
    
    reversed_dict = defaultdict(list)
    for key, value in mydict.items():
        reversed_dict[value].append(key)
    

提交回复
热议问题