[Python-Dev] dict.addlist() (original) (raw)
Raymond Hettinger python at rcn.com
Tue Jan 20 13:32:33 EST 2004
- Previous message: [Python-Dev] dict.addlist()
- Next message: [Python-Dev] dict.addlist()
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
[GvR]
> bookindex = dict()
(What's wrong with {}?)
Nothing at all. {} is shorter, faster, and everyone understands it.
When teasing out ideas at the interpreter prompt, I tend to use dict() because I find it easier to edit the line and add some initial values using dict(one=1, two=2, s='abc').
works for me. (I think setdefault() was already a minor mistake -- by the time I've realized it applies I have already written working code without it. And when using setdefault() I always worry about the waste of the new empty list passed in each time that's ignored most times.)
If you really want library support for this idiom ...
Not really. It was more of a time machine question -- if we had setdefault() to do over again, what would be done differently:
- Keep setdefault().
- Drop it and make do with get(), try/except, or if k in d.
- Martin's idea for dicts to have an optional factory function for defaults.
- Have a specialized method that just supports dicts of lists.
After all the discussions, the best solution to the defaulting problem appears to be some variant of Martin's general purpose approach:
d = {} d.setfactory(list) for k, v in myitems: d[k].append(v) # dict of lists
d = {} d.setfactory(set): for v in mydata: d[f(v)].add(v) # partition into equivalence classes
d = {} d.setfactory(int): for v in mydata: d[k] += 1 # bag
Raymond Hettinger
- Previous message: [Python-Dev] dict.addlist()
- Next message: [Python-Dev] dict.addlist()
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]