python反转字典的键和值,如何反转一个字典它已重复的值(python)

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}

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.

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)

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值