How to change the dictionary so that it repeats the values

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!

+6
source share
5 answers
 from collections import defaultdict reversed_dict = defaultdict(list) for key,value in mydict.iteritems(): reversed_dict[value].append(key) 

Please do not use dict as a variable, this interferes with the dict () function

+10
source

I think you lose a few cycles, replacing the 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) 
+2
source
 for k,v in dict.iteritems(): try: reversed_dict[v].append(k) except KeyError: reversed_dict[v]=[k] 
+1
source
 reversed_dict = collections.defaultdict(list) for key, value in dict_.iteritems(): reversed_dict[value].append(key) 
0
source

Using itertools.groupby :

 from operator import itemgetter from itertools import groupby snd = itemgetter(1) def sort_and_group(itr, f): return groupby(sorted(itr, key=f), f) mydict = {'a': 1, 'c': 2, 'b': 1, 'e': 2, 'd': 3, 'h': 1, 'j': 3} reversed_dict = {number: [char for char,_ in v] for number, v in sort_and_group(mydict.items(), snd)} 
0
source

Source: https://habr.com/ru/post/1309603/


All Articles