Pre-PEP: Dictionary accumulator methods
Brian van den Broek
bvande at po-box.mcgill.ca
Fri Mar 18 23:45:03 EST 2005
Raymond Hettinger said unto the world upon 2005-03-18 20:24:
> I would like to get everyone's thoughts on two new dictionary methods:
>
> def count(self, value, qty=1):
> try:
> self[key] += qty
> except KeyError:
> self[key] = qty
>
> def appendlist(self, key, *values):
> try:
> self[key].extend(values)
> except KeyError:
> self[key] = list(values)
>
> 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)
<SNIP>
Hi all,
I am *far* less experienced with Python and programming than those
who've weighed in as yet.
I quite like count, though I agree with posts up thread that `count'
might not be the best name.
For appendlist, I would have expected
def appendlist(self, key, sequence):
try:
self[key].extend(sequence)
except KeyError:
self[key] = list(sequence)
I am, however, very open to the possibility that this says more about
my level of experience than it does about which way is best :-)
Best to all,
Brian vdB
More information about the Python-list
mailing list