Re: Check for dict key existence, and modify it in one step.



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@xxxxxxxx>

.



Relevant Pages

  • Re: Exception not raised
    ... Michele Petrazzo wrote: ... def test: ... <type 'dict'> ... but a subclass of it? ...
    (comp.lang.python)
  • Re: save class
    ... it, but my ideal would be to have the base class, Map, be able to make ... def DoSomething: ... its own dict, not different *subclasses*. ... problem (subclass an abstract base class that calls specific methods on ...
    (comp.lang.python)
  • Re: save class
    ... it, but my ideal would be to have the base class, Map, be able to make ... def DoSomething: ... From the above description I feel you want just different Map *instances*, each with its own dict, not different *subclasses*. ... and that his solution sounds like a Java approach to the problem (subclass an abstract base class that calls specific methods on the subclass to "do the right thing"). ...
    (comp.lang.python)