Pre-PEP: Dictionary accumulator methods

El Pitonero pitonero at gmail.com
Sat Mar 19 05:24:24 EST 2005


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)

Bengt Richter wrote:
>  >>> class xdict(dict):
>  ...     def valadd(self, key, incr=1):
>  ...         try: self[key] = self[key] + type(self[key])(incr)
>  ...         except KeyError: self[key] = incr

What about:

import copy
class safedict(dict):
    def __init__(self, default=None):
        self.default = default
    def __getitem__(self, key):
        try:
            return dict.__getitem__(self, key)
        except KeyError:
            return copy.copy(self.default)

x = safedict(0)
x[3] += 1
y = safedict([])
y[5] += range(3)
print x, y
print x[123], y[234]




More information about the Python-list mailing list