[Python-Dev] defaultdict proposal round three (original) (raw)
Ian Bicking ianb at colorstudy.com
Mon Feb 20 22:13:27 CET 2006
- Previous message: [Python-Dev] defaultdict proposal round three
- Next message: [Python-Dev] defaultdict proposal round three
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Steven Bethard wrote:
Alternative A: add a new method to the dict type with the semantics of getattr from the last proposal, using defaultfactory if not None (except onmissing is inlined).
I'm not certain I understood this right but (after s/getattr/getitem) this seems to suggest that for keeping a dict of counts the code wouldn't really improve much: dd = {} dd.defaultfactory = int for item in items: # I want to do
dd[item] += 1but with a regular method instead # of getitem, this is not possible dd[item] = dd.somenewmethod(item) + 1
This would be better done with a bag (a set that can contain multiple instances of the same item):
dd = collections.Bag() for item in items: dd.add(item)
Then to see how many there are of an item, perhaps something like: dd.count(item)
No collections.Bag exists, but of course one should. It has nice properties -- inclusion is done with contains (with dicts it probably has to be done with get), you can't accidentally go below zero, the methods express intent, and presumably it will implement only a meaningful set of methods.
-- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org
- Previous message: [Python-Dev] defaultdict proposal round three
- Next message: [Python-Dev] defaultdict proposal round three
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]