How to reverse a dictionary that has repeated values

后端 未结 6 1812
抹茶落季
抹茶落季 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:14

    I think you're wasting a few cycles by replacing a key with the same key again and again...

    reversed_dict = {}
    for value in mydict.values():
        if value not in reversed_dict.keys(): #checking to be sure it hasn't been done.
            reversed_dict[value] = []
            for key in mydict.keys():
                if mydict[key] == value:
                    if key not in reversed_dict[value]: reversed_dict[value].append(key)
    

提交回复
热议问题