'inverting' a dict
Bob van der Poel
bvdpoel at kootenay.com
Wed Dec 31 21:23:04 EST 2003
This is sort of off topic for the thread, but I've got a similar
problem. In this case I have a dict like:
{ 'key1': 'value1', 'key2': value2}
and I sometimes need to find the key for the value. All values/keys are
unique. I just use a loop:
for a in dict:
if dict[a]== targ:
return a
return None
But it'd be nice to have something faster, etc.
Elaine Jackson wrote:
> dict2=dict([(a,b) for b in dict1.keys() for a in dict1[b]])
>
> HTH
>
>
> "Irmen de Jong" <irmen at -NOSPAM-REMOVETHIS-xs4all.nl> wrote in message
> news:3ff1b688$0$319$e4fe514c at news.xs4all.nl...
> | 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.
> |
>
>
--
Bob van der Poel ** Wynndel, British Columbia, CANADA **
EMAIL: bvdpoel at kootenay.com
WWW: http://www.kootenay.com/~bvdpoel
More information about the Python-list
mailing list