Re: 'inverting' a dict
Irmen de Jong <irmen@-NOSPAM-REMOVETHIS-xs4all.nl> writes:
[color=blue]
> 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:[/color]
That's almost spooky, I'm working on a project for which I needed
something like this. I've just read the entire thread and my solution
seems pretty naive:
def invertdict(d):
"""Returns a dict whose key-value pairs are the value-key pairs of d."""
ret = {}
for k in d:
ret[d[k]] = k
return ret
I only need to do it once or twice, at program start-up, so time-
efficiency wasn't a critical factor. I'm guessing the list
comprehension tactics are faster, though.
Sorry about being late to the party, I've been away from Usenet for
about three weeks...
Nick
--
# sigmask || 0.2 || 20030107 || public domain || feed this to a python
print reduce(lambda x,y:x+chr(ord(y )-1),' Ojdl!Wbshjti!=o bwAcboefstobudi/psh?')
Irmen de Jong <irmen@-NOSPAM-REMOVETHIS-xs4all.nl> writes:
[color=blue]
> 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:[/color]
That's almost spooky, I'm working on a project for which I needed
something like this. I've just read the entire thread and my solution
seems pretty naive:
def invertdict(d):
"""Returns a dict whose key-value pairs are the value-key pairs of d."""
ret = {}
for k in d:
ret[d[k]] = k
return ret
I only need to do it once or twice, at program start-up, so time-
efficiency wasn't a critical factor. I'm guessing the list
comprehension tactics are faster, though.
Sorry about being late to the party, I've been away from Usenet for
about three weeks...
Nick
--
# sigmask || 0.2 || 20030107 || public domain || feed this to a python
print reduce(lambda x,y:x+chr(ord(y )-1),' Ojdl!Wbshjti!=o bwAcboefstobudi/psh?')
Comment