try vs. has_key()

Moshe Zadka moshez at math.huji.ac.il
Fri Apr 23 07:13:59 EDT 1999


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.






More information about the Python-list mailing list