Pre-PEP: Dictionary accumulator methods

Ron radam2 at tampabay.rr.com
Sat Mar 19 18:10:40 EST 2005


On 19 Mar 2005 11:33:20 -0800, "Kay Schluehr" <kay.schluehr at gmx.net>
wrote:

>Raymond Hettinger 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)
>
>-1 form me.
>
>I'm not very glad with both of them ( not a naming issue ) because i
>think that the dict type should offer only methods that apply to each
>dict whatever it contains. count() specializes to dict values that are
>addable and appendlist to those that are extendable. Why not
>subtractable, dividable or right-shiftable? Because of majority
>approval? I'm mot a speed fetishist and destroying the clarity of a
>very fundamental data structure for speedup rather arbitrary
>accumulations seems to be a bad idea. I would move this stuff in a
>subclass.
>
>Regards Kay

-1 for me too.

I agree with this.  The other dictionary functions are all data
nuetral.  Adding special methods to handle data should be in a
durrived class and not a built in.  imho.

# Roll your own specialized dictionaries.

class NumDict( dict):
    def count(self, key, 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)

mydict = NumDict()

n = 0
for k in list('abcdefg'):
    n += 1
    mydict[k] = n

print mydict
# {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6}

mydict.count('c')
mydict['e'] = ['a']
mydict.appendlist('e', 'bcdef')
print mydict
# {'a': 1, 'c': 4, 'b': 2, 'e': ['a', 'bcdef'], 'd': 4, 'g': 7, 'f':
6}


This isn't that hard to do.  I don't think the extra methods should be
added to the base class.

Ron




More information about the Python-list mailing list