Pre-PEP: Dictionary accumulator methods

David Eppstein eppstein at ics.uci.edu
Sat Mar 19 23:47:03 CET 2005


In article <JbL_d.8237$qN3.2116 at trndny01>,
 "Raymond Hettinger" <vze4rx4y at verizon.net> wrote:

> 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)
> 
> In their multi-value forms, they would now be coded as:
> 
>   d.count(key, qty)
>   d.appendlist(key, *values)
> 
> The error messages returned by the new methods are the same as those returned 
> by
> the existing idioms.
> 
> The get() method would continue to exist because it is useful for 
> applications
> other than accumulation.
> 
> The setdefault() method would continue to exist but would likely not make it
> into Py3.0.

The other dictionary based accumulation I've used but don't see here is 
with sets as dictionary values, i.e. 
    dictionary.setdefault(key,set()).add(value).

I suppose it would be possible to appendlist then make a set from the 
list, but if you were to take that minimalist philosophy to an extreme 
you wouldn't need count either, you could just appendlist then use len.

-- 
David Eppstein
Computer Science Dept., Univ. of California, Irvine
http://www.ics.uci.edu/~eppstein/



More information about the Python-list mailing list