try vs. has_key()

Gordon McMillan gmcm at hypernet.com
Thu Apr 22 21:55:55 EDT 1999


Aahz asks:

> I've seen roughly half the people here doing
> 
> try:
>    dict[key].append(foo)
> except:
>    dict[key]=[foo]
> 
> with the other half doing
> 
> if dict.has_key(key):
>    dict[key].append(foo)
> else:
>    dict[key]=[foo]
> 
> Can people explain their preferences?

I have done both. Option 1 requires slightly less typing, but is only 
better when you (in practice) have a dict with a small number of keys 
and rather longish lists. (In Python, "try" is damned near free, and 
"except" is a lot cheaper than, say, C++'s "catch", but still costs a 
good deal more than has_key.)

Conscientious practice of option 2, of course, allows you to look St. 
Peter in the eye and demand entrance without fear of contradiction...

- Gordon




More information about the Python-list mailing list