Pre-PEP: Dictionary accumulator methods

Carl Banks invalidemail at
Sat Mar 19 13:18:50 CET 2005

Raymond Hettinger wrote:
> I would like to get everyone's thoughts on two new dictionary
>         def count(self, value, qty=1):
>             try:
>                 self[key] += qty
>             except KeyError:
>                 self[key] = qty
>         def appendlist(self, key, *values):
>             try:
>                 self[key].extend(values)
>             except KeyError:
>                 self[key] = list(values)

Emphatic +1

I use both of these idioms all the time.  (Kind of surprised to see
people confused about the need for the latter; I do it regularly.)
This is just the kind of thing experience shows cropping up enough that
it makes sense to put it in the language.

About the names: Seeing that these have specific uses, and do something
that is hard to explain in one word, I would suggest that short names
like count might betray the complexity of the operations.  Therefore,
I'd suggest:

increment_value() (or add_to_value())

Although they don't explicitly communicate that a value would be
created if it didn't exist, they do at least make it clear that it
happens to the value, which kind of implies that it would be created.

If we do have to use short names:

I don't like increment (or inc or incr) at all because it has the air
of a mutator method.  Maybe it's just my previous experience with Java
and C++, but to me, a.incr() looks like it's incrementing a, and
a.incr(b) looks like it might be adding b to a.  I don't like count
because it's too vague; it's pretty obvious what it does as an
iterator, but not as a method of dict.  I could live with tally,
though.  As for a short name for the other one, maybe fileas or


More information about the Python-list mailing list