rodrigo a écrit :
> You're right of course, I was unclear. I wasn't using 'dict' to
> override the dict clas, but just as a standin for the example (the
> actual dictionary names are varied).
I guessed so, but Python's behaviour wrt/ naming can be somewhat
surprising for newcomers, and accidental
On Aug 28, 1:13 pm, rodrigo <[EMAIL PROTECTED]> wrote:
> evan,
>
> yes, it does help. Works like it should:
>
> class CountingDictionary(dict):
> def increment(self, key, delta=1):
> self[key] = self.get(key, 0) + delta
>
> d = CountingDictionary()
> d.increment('cat')
> d.increment('do
Ben Finney <[EMAIL PROTECTED]> writes:
> foo.setdefault(whatever, {})
> foo[whatever].setdefault(someother, 0)
> foo[whatever] += delta
Should, of course, be:
foo.setdefault(whatever, {})
foo[whatever].setdefault(someother, 0)
foo[whatever][someother] += delta
--
\
rodrigo <[EMAIL PROTECTED]> writes:
> Im using this construct a lot:
>
> if dict.has_key(whatever):
> dict[whatever] += delta
> else:
> dict[whatever] = 1
I'd prefer:
foo.setdefault(whatever, 0)
foo[whatever] += delta
> sometimes even nested:
>
> if dict.has_key(whatever):
>
You're right of course, I was unclear. I wasn't using 'dict' to
override the dict clas, but just as a standin for the example (the
actual dictionary names are varied).
Thanks,
Rodriog
--
http://mail.python.org/mailman/listinfo/python-list
evan,
yes, it does help. Works like it should:
class CountingDictionary(dict):
def increment(self, key, delta=1):
self[key] = self.get(key, 0) + delta
d = CountingDictionary()
d.increment('cat')
d.increment('dog',72)
print d
>>> {'dog': 72, 'cat': 1}
Thanks!
--
http://mail.python
On Tue, 2007-08-28 at 14:36 +, 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):
On Aug 28, 8:36 am, rodrigo <[EMAIL PROTECTED]> wrote:
> Im using this construct a lot:
>
> if dict.has_key(whatever):
> dict[whatever] += delta
> else:
> dict[whatever] = 1
>
> sometimes even nested:
>
> if dict.has_key(whatever):
> if dict[whatever].has_key(someother):
> dict[
rodrigo a écrit :
> Im using this construct a lot:
>
> if dict.has_key(whatever):
Avoid using builtin names as identifiers (it shadows the builtin name).
Unless you're using an old Python version, you'd be better using
if whatever in my_dict:
# do something here
> dict[whatever] +
Im using this construct a lot:
if dict.has_key(whatever):
dict[whatever] += delta
else:
dict[whatever] = 1
sometimes even nested:
if dict.has_key(whatever):
if dict[whatever].has_key(someother):
dict[whatever][someother] += delta
else:
dict[whatever][someother] =
10 matches
Mail list logo