How to reverse a dictionary that it has repeated values (python)

Posted by Galois on Stack Overflow See other posts from Stack Overflow or by Galois
Published on 2010-05-12T22:48:35Z Indexed on 2010/05/12 22:54 UTC
Read the original article Hit count: 147

Filed under:

Hi guys! So, I have a dictionary with almost 100,000 (key, values) pairs and the majority of the keys map to the same values. For example imagine something like that:

dict =  {'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 dict is going to be a key at the reverse_dict and is going to map to a list of all the dict.keys that used to map to that value at the dict. So based on the example above I would get:

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

I came up with a solution that is very expensive and I would really want to hear any ideas more efficient than mine.

my expensive solution:

reversed_dict = {}
for value in dict.values():
    reversed_dict[value] = []
    for key in dict.keys():
        if dict[key] == value:
            if key not in reversed_dict[value]: reversed_dict[value].append(key)

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

I would really appreciate to hear any ideas better and more efficient than than mine. Thanks!

© Stack Overflow or respective owner

Related posts about python