如何反转一个字典它已重复的值(python) [英] How to reverse a dictionary that it has repeated values (python)

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

问题描述

所以,我有一个几乎有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的列表在mydict的价值。所以根据上面的例子,我会得到:

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.

我的昂贵的解决方案: / p>

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 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.iteritems():
    reversed_dict[value].append(key)

请不要将dict用作变量,这与函数dict()相冲突

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

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

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