'inverting' a dict

engsolnom at ipns.com engsolnom at ipns.com
Tue Dec 30 20:44:05 CET 2003


On Tue, 30 Dec 2003 18:30:56 +0100, Irmen de Jong
<irmen at -NOSPAM-REMOVETHIS-xs4all.nl> 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.

I had a need for a 'reverse' dictionary also. This is how I approached
it:

source_dict = {'A': 1,'B': 2,'C': 3,'D': 4}
target_dict = {}
for item in source_dict.iteritems():
    target_dict[item[1]] = item[0]

Or, a bit more contrived....

source_dict = {'A': [[1,2,3],100],'B': [[4,5,6],200],'C':
[[7,8,9],300]}
target_dict = {}
for item in source_dict.iteritems():
    target_dict[item[1][1]] = item[0]

Disclaimer: I'm a newbie 
Norm






More information about the Python-list mailing list