'inverting' a dict

From: Irmen de Jong (irmen_at_-NOSPAM-REMOVETHIS-xs4all.nl)
Date: 12/30/03


Date: Tue, 30 Dec 2003 18:30:56 +0100

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.



Relevant Pages

  • Re: Mexican Laetoli?
    ... > footprints being hominid vs some sort of chimera of other animals ... The maps they show of the Toluquilla ... of a 3-4 print sequence leading nowhere. ... trail of striding humans eventually can be demonstrated. ...
    (sci.anthropology.paleo)
  • Re: inverting a dict
    ... >I have this dict that maps a name to a sequence of other names. ... I had a need for a 'reverse' dictionary also. ...
    (comp.lang.python)
  • help, its urgent
    ... R^n --> R^a denotes the projection, ... and pi o g the product of composition of such maps g and pi. ... there exists a sequence _k in R^n ... I know that by Morse-Sard theorem the set of regular value ...
    (sci.math)
  • Re: Stretched Contenents?
    ... Here is a link to a page with only the maps. ... a sequence from the Jurassic to the late Miocene illustrating the evolution ...
    (sci.geo.geology)
  • Re: inverting a dict
    ... HTH ... | I have this dict that maps a name to a sequence of other names. ...
    (comp.lang.python)