Pre-PEP: Dictionary accumulator methods
Kent Johnson
kent37 at tds.net
Sat Mar 19 07:13:15 EST 2005
Bengt Richter wrote:
> On Sat, 19 Mar 2005 01:24:57 GMT, "Raymond Hettinger" <vze4rx4y at verizon.net> wrote:
>
>>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)
>>
> How about an efficient duck-typing value-incrementer to replace both? E.g. functionally like:
>
> >>> class xdict(dict):
> ... def valadd(self, key, incr=1):
> ... try: self[key] = self[key] + type(self[key])(incr)
> ... except KeyError: self[key] = incr
A big problem with this is that there are reasonable use cases for both
d.count(key, <some integer>)
and
d.appendlist(key, <some integer>)
Word counting is an obvious use for the first. Consolidating a list of key, value pairs where the
values are ints requires the second.
Combining count() and appendlist() into one function eliminates the second possibility.
Kent
More information about the Python-list
mailing list