如何反转具有重复值的字典 [英] How to reverse a dictionary that has repeated values

查看:55
本文介绍了如何反转具有重复值的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本字典,其中有将近100,000个(键,值)对,并且大多数键都映射到相同的值。例如:

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}

我想做的是反转字典,以便 mydict 中的每个值都将成为 reverse_dict 的键,并映射到用于映射到 mydict 中该值的所有 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 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)


推荐答案

使用 collections.defaultdict

from collections import defaultdict

reversed_dict = defaultdict(list)
for key, value in mydict.items():
    reversed_dict[value].append(key)

这篇关于如何反转具有重复值的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆