The rap against "while True:" loops
Sat Oct 17 23:05:50 CEST 2009
aahz at pythoncraft.com (Aahz) writes:
> > d = collections.defaultdict(int)
> > ...
> > d[key] += value
> That was a trivial example; non-trivial examples not addressed by
> defaultdict are left as an exercise for the reader.
Even in the "nontrivial" examples, I think avoiding the exception is
d[key] = value + d.get(key, 0)
It might be worth handling the exception in an inner loop where you
want to avoid the cost of looking up key in the dictionary twice, but
even that requires profiling to be sure.
More information about the Python-list