'inverting' a dict
sdd
daniels at dsl-only.net
Thu Jan 1 17:31:01 EST 2004
Bob van der Poel wrote:
> 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
For a few hunts, I'd do:
for key,value in dictionary.iteritems():
if value == target:
return key
return None
Of course, if it probed a lot between changes, it's better to
reversedictionary = dict([(v,k) for k,v in dictionary.items()])
-Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list