反转原始字典的键和值 [英] Invert keys and values of the original dictionary

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

问题描述

例如,我通过传递字典作为参数来调用此函数:

 >>> inv_map({'a':1,'b':2,'c':3,'d':2})
{1:['a'],2:['b' '],3:['c']}
>>> inv_map({'a':3,'b':3,'c':3})
{3:['a','c','b']}
>> ;> inv_map({'a':2,'b':1,'c':2,'d':1})
{1:['b','d'],2: ','c']}

如果

  map = {'a':1,'b':2} 

我只能反转这个地图来获取:

  inv_map = {1:'a',2:' b'} 

使用此

  dict((v,k)for k,v in map.iteritems())

任何人都知道如何处理我的情况?

解决方案

您可以使用defaultdict与列表: / p>

 >>> from collections import defaultdict 
>>>> m = {'a':2,'b':1,'c':2,'d':1}
>>> dd = defaultdict(list)
>>>对于k,v在m.iteritems()中:
... dd [v] .append(k)
...
>>> dict(dd)
{1:['b','d'],2:['a','c']}

如果您不关心如果您有dict或defaultdict,则可以直接删除最后一步而不使用defaultdict。


For example, I call this function by passing a dictionary as parameter:

>>> inv_map({'a':1, 'b':2, 'c':3, 'd':2})
{1: ['a'], 2: ['b', 'd'], 3: ['c']}
>>> inv_map({'a':3, 'b':3, 'c':3})
{3: ['a', 'c', 'b']}
>>> inv_map({'a':2, 'b':1, 'c':2, 'd':1})
{1: ['b', 'd'], 2: ['a', 'c']}

If

map = { 'a': 1, 'b':2 }

I can only invert this map to get:

inv_map = { 1: 'a', 2: 'b' }

by using this

dict((v,k) for k, v in map.iteritems())

Anyone knows how to do that for my case?

解决方案

You can use a defaultdict with list:

>>> from collections import defaultdict
>>> m = {'a': 2, 'b': 1, 'c': 2, 'd': 1}
>>> dd = defaultdict(list)
>>> for k, v in m.iteritems():
...     dd[v].append(k)
... 
>>> dict(dd)
{1: ['b', 'd'], 2: ['a', 'c']}

If you don't care if you have an dict or defaultdict, you can omit the last step und use the defaultdict directly.

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

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