Pre-PEP: Dictionary accumulator methods

David Eppstein eppstein at ics.uci.edu
Sun Mar 20 18:14:22 EST 2005


In article <d1koii$2vp$1 at panix2.panix.com>, aahz at pythoncraft.com (Aahz) 
wrote:

> >I am surprised nobody suggested we put those two methods into a
> >separate module (say dictutils or even UserDict) as functions:
> >
> >from dictutils import tally, listappend
> >
> >tally(mydict, key)
> >listappend(mydict, key, value)
> 
> That seems like a reasonable compromise.

The more messages I see on this thread, the more I think adding a 
different new method for each commonly used kind of update is the wrong 
solution.

We already have methods that work pretty well and, I think, read better 
than the new methods:
  mydict[key] += 1
  mydict[key].append(value)
The problem is merely that they don't work when key is missing, so we 
need to resort to setdefault circumlocutions instead.  A better solution 
seems to be the one I've seen suggested here several times, of changing 
the dict's behavior so that the setdefault is automatic whenever trying 
to access a missing key.  If this would be in a separate module or 
separate subclass of dict, so much the better.

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



More information about the Python-list mailing list