wasm-demo/demo/ermis-f/python_m/cur/0096

67 lines
1.8 KiB
Plaintext

From: moshez at math.huji.ac.il (Moshe Zadka)
Date: Fri, 23 Apr 1999 14:13:59 +0300
Subject: try vs. has_key()
In-Reply-To: <yWOT2.6007$8m5.9320@newsr1.twcny.rr.com>
References: <aahzFAM4oJ.M7M@netcom.com> <yWOT2.6007$8m5.9320@newsr1.twcny.rr.com>
Message-ID: <Pine.SUN.3.95-heb-2.07.990423140345.21577A-100000@sunset.ma.huji.ac.il>
Content-Length: 1457
X-UID: 96
Note:
This article is a non-commercial advertisement for the ``get'' method
of dictionary objects.
Brought to you by the object None and the method .append.
On Thu, 22 Apr 1999, Darrell wrote:
> My experience shows that throwing an exception is slower.
>
> Aahz Maruch <aahz at netcom.com> wrote in message
> news:aahzFAM4oJ.M7M at netcom.com...
> > I've seen roughly half the people here doing
> >
<snipped try/except idiom for updating a dictionary>
<snipped has_key idiom for updating a dictionary>
It depends on the expected hit/miss ratio.
If you have many hits, few misses -- use the first
Few hits, many misses -- use the second.
Best way is to use
(for example, counting)
d={}
for word in words:
d[word]=d.get(word, 0)+1
Or, for logging:
d={}
for word in words:
first_two=word[:2]
d[first_two]=d.get(first_two, []).append(word)
Unfortunately, few people seem to know about the ``get'' method, which
is really good.
>From the docs:
a.get(k[, f]) the item of a with key k (4)
(4)
Never raises an exception if k is not in the map, instead it
returns f. f is optional, when not provided and k is not in the
map, None is returned.
This makes dictionary types behave in a Perl-hash-like manner, which is
sometimes a good thing.
Note that this idiom is (I think) more efficient, and shorter.
--
Moshe Zadka <mzadka at geocities.com>.
QOTD: What fun to me! I'm not signing permanent.