因此,我有一本字典,其中包含将近100,000个(键,值)对,并且大多数键都映射到相同的值.例如,想象一下这样的事情:
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:
mydict = {'a': 1, 'c': 2, 'b': 1, 'e': 2, 'd': 3, 'h': 1, 'j': 3}我想做的是反转字典,以便mydict中的每个值都将成为reverse_dict的键,并要映射到用于映射到该值的所有mydict.keys的列表.在神秘的故事.因此,根据以上示例,我将得到:
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 at the mydict. 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.
我昂贵的解决方案:
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 really appreciate to hear any ideas better and more efficient than than mine. Thanks!
推荐答案from collections import defaultdict reversed_dict = defaultdict(list) for key, value in mydict.items(): reversed_dict[value].append(key)
请不要将dict用作变量,这会与内置函数dict()冲突
Please do not use dict as a variable, this collides with builtin function dict()
更多推荐
如何反转具有重复值的字典
发布评论