Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse a dictionary that has repeated values

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, 'b': 1, 'e': 2, 'd': 3, 'h': 1, 'j': 3}

What I want to do, is to reverse the dictionary so that each value in mydict is going to be a key at the reverse_dict and is going to map to a list of all the mydict.keys() that used to map to that value in mydict. So based on the example above I would get:

reversed_dict = {1: ['a', 'b', 'h'], 2: ['c', 'e'] , 3: ['d', 'j']} 

I came up with a solution that is very expensive and I want to hear any ideas for doing this more efficiently than this:

reversed_dict = {}
for value in mydict.values():
    reversed_dict[value] = []
    for key in mydict.keys():
        if mydict[key] == value:
            if key not in reversed_dict[value]: 
                reversed_dict[value].append(key)
like image 965
Galois Avatar asked May 12 '10 22:05

Galois


1 Answers

Using collections.defaultdict:

from collections import defaultdict

reversed_dict = defaultdict(list)
for key, value in mydict.items():
    reversed_dict[value].append(key)
like image 161
joaquin Avatar answered Sep 20 '22 16:09

joaquin