Pre-PEP: Dictionary accumulator methods
Alexander Schmolck
a.schmolck at gmx.net
Sat Mar 19 20:26:41 EST 2005
"Raymond Hettinger" <vze4rx4y at verizon.net> writes:
> The rationale is to replace the awkward and slow existing idioms for dictionary
> based accumulation:
>
> d[key] = d.get(key, 0) + qty
> d.setdefault(key, []).extend(values)
>
> In simplest form, those two statements would now be coded more readably as:
>
> d.count(key)
> d.appendlist(key, value)
Yuck.
The relatively recent "improvement" of the dict constructor signature
(``dict(foo=bar,...)``) obviously makes it impossible to just extend the
constructor to ``dict(default=...)`` (or anything else for that matter) which
would seem much less ad hoc. But why not use a classmethod (e.g.
``d=dict.withdefault(0)``) then?
Or, for the first and most common case, just a bag type?
'as
More information about the Python-list
mailing list