So, I have a dictionary with almost 100,000 (key, values), and most keys are mapped to the same values. For example, imagine something like this:
mydict = {'a': 1, 'c': 2, 'b': 1, 'e': 2, 'd': 3, 'h': 1, 'j': 3}
What I want to do is flip the dictionary so that each value in mydict is a key in the reverse_dicton and is about to display a list of all mydict.keys that were used to match this value with the midicon. Therefore, based on the above example, 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 really would like to hear any ideas more effective than mine.
my expensive solution:
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) Output >> reversed_dict = {1: ['a', 'b', 'h'], 2: ['c', 'e'], 3: ['d', 'j']}
I would be glad to hear any ideas better and more effective than mine. Thanks!