'inverting' a dict

Yermat loic at yermat.net1.nerim.net
Tue Dec 30 16:12:05 EST 2003


or even shorter
>>> d = {'key1' : ('value1','value2'), 'key2': ('value3',) }

>>> dict([(v,k) for k in d.iterkeys() for v in d[k]])
{'value3': 'key2', 'value2': 'key1', 'value1': 'key1'}


"anton muhin" <antonmuhin at rambler.ru> a écrit dans le message de
news:bssgf2$10nt3$1 at ID-217427.news.uni-berlin.de
> Irmen de Jong wrote:
>> Hi
>> I have this dict that maps a name to a sequence of other names.
>> I want to have it reversed, i.e., map the other names each to
>> the key they belong to (yes, the other names are unique and
>> they only occur once). Like this:
>>
>> { "key1": ("value1", "value2"), "key2": ("value3,) }
>>
>> -->
>>
>> { "value1": "key1", "value2": "key1", "value3": "key2" }
>>
>> What I'm doing is using a nested loop:
>>
>> dict2={}
>> for (key,value) in dict1.items():
>>     for name in value:
>>         dict2[name] = key
>>
>> which is simple enough, but I'm hearing this little voice in
>> the back of my head saying "there's a simpler solution".
>> Is there? What is it? ;-)
>>
>> Thanks
>> --Irmen.
>>
>
> It's seems like rather nice Python for me ;). Two more variants:
>
> inverted = {}
> for k, vs in d.iteritems():
>      inverted.update(dict([(v, k) for v in vs]))
>
> map(
>     lambda (k, vs): inverted.update(dict([(v, k) for v in vs])),
>     d.iteritems()
> )
>
> happy new year,
> anton.






More information about the Python-list mailing list