如何反转具有重复值的字典

编程入门 行业动态 更新时间:2024-10-08 13:38:20
本文介绍了如何反转具有重复值的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

因此,我有一本字典,其中包含将近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()

更多推荐

如何反转具有重复值的字典

本文发布于:2023-07-19 13:44:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1157094.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!