gather information from various files efficiently

Fredrik Lundh fredrik at pythonware.com
Tue Dec 14 07:28:35 EST 2004


Keith Dart wrote:

>>> try:
>>>     dict[a].append(b)
>>> except KeyError:
>>>     dict[a] = [b]

the drawback here is that exceptions are relatively expensive; if the
number of collisions are small, you end up throwing and catching lots
of exceptions.  in that case, there are better ways to do this.

>>     dict.setdefault(a, []).append(b)

the drawback here is that you create a new object for each call, but
if the number of collisions are high, you end up throwing most of them
away.  in that case, there are better ways to do this.

(gotta love that method name, btw. a serious candidate for the "most
confusing name in the standard library" contest...  or maybe even the
"most confusing name in the history of python" contest...)

> Hey, when did THAT get in there? ;-) That's nice. However, the try..except block is a useful 
> pattern for many similiar situations that the OP might want to keep in mind. It is usually better 
> than the following, also:
>
> if dct.has_key(a):
>     dct[a].append(b)
> else:
>     dct[a] = [b]

the drawback here is that if the number of collisions are high, you end
up doing lots of extra dictionary lookups.  in that case, there are better
ways to do this.

</F> 






More information about the Python-list mailing list