Check for dict key existence, and modify it in one step.
Evan Klitzke
evan at yelp.com
Tue Aug 28 11:43:12 EDT 2007
On Tue, 2007-08-28 at 14:36 +0000, rodrigo wrote:
> Im using this construct a lot:
>
> if dict.has_key(whatever):
> dict[whatever] += delta
> else:
> dict[whatever] = 1
In Python 2.5 there's a defaultdict class, otherwise you can subclass
dict like this:
class CountingDictionary(dict):
def increment(self, key, delta=1):
self[key] = self.get(key, 0) + delta
Hope this helps!
--
Evan Klitzke <evan at yelp.com>
More information about the Python-list
mailing list