# Pre-PEP: Dictionary accumulator methods

Bengt Richter bokr at oz.net
Sat Mar 19 22:13:31 CET 2005

```On Sat, 19 Mar 2005 07:13:15 -0500, Kent Johnson <kent37 at tds.net> wrote:

>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.
I don't see a "big problem" ;-)

d.addval doesn't eliminate the functionalities if you want them. You just have to spell them
and
respectively.

My example interactive stuff in a previous post shows both of these using xd['x'] and xd.['y']:
"""
>>> xd = xdict()
>>> xd
{}

Default integer 1 arg creates initial int value
>>> xd
{'x': 1}

Explicit list arg create initial list value
>>> xd
{'y': [0, 1, 2], 'x': 1}

Explicit int increment adds to existing int
>>> xd['x']
101

Explicit list arg extends existing list with contents of increment list
which you can of course optionally use with a length-1 list to achieve the .append effect
>>> xd['y']
[0, 1, 2, 3, 4, 5]
"""

Granted, d.appendlist will result in more efficient code, since the temp list arg
[<some integer>] does not have to be created and the type of the existing dict value
does not have to be tested as generally. OTOH, you can create and extend tuple
or even custom object values using valadd, and extend with alternate sequences that
get converted to the existing type if its contructor knows how to accept alternatives.

So I think you are not prevented from doing anything. IMO Raymond's Zen concerns
are the ones to think about first, and then efficiency, which was one of the motivators
in the first place ;-)

Regards,
Bengt Richter

```