41 lines
1.0 KiB
Plaintext
41 lines
1.0 KiB
Plaintext
From: gmcm at hypernet.com (Gordon McMillan)
|
|
Date: Fri, 23 Apr 1999 01:55:55 GMT
|
|
Subject: try vs. has_key()
|
|
In-Reply-To: <aahzFAM4oJ.M7M@netcom.com>
|
|
References: <aahzFAM4oJ.M7M@netcom.com>
|
|
Message-ID: <1287289735-37704702@hypernet.com>
|
|
X-UID: 93
|
|
|
|
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
|
|
|
|
|
|
|
|
|