Pre-PEP: Dictionary accumulator methods

George Sakkis gsakkis at rutgers.edu
Mon Mar 21 16:09:09 EST 2005


"Michele Simionato" <michele.simionato at gmail.com> wrote:

> FWIW, here is my take on the defaultdict approach:
>
> def defaultdict(defaultfactory, dictclass=dict):
>     class defdict(dictclass):
>         def __getitem__(self, key):
>             try:
>                 return super(defdict, self).__getitem__(key)
>             except KeyError:
>                 return self.setdefault(key, defaultfactory())
>     return defdict
>
> d = defaultdict(int)()
> d["x"] += 1
> d["x"] += 1
> d["y"] += 1
> print d
>
> d = defaultdict(list)()
> d["x"].append(1)
> d["x"].append(2)
> d["y"].append(1)
> print d
>
>               Michele Simionato


Best solution so far. If it wasn't for the really bad decision to add the dict(**kwargs)
constructor, I'd love to see something like
d = dict(valType=int)
d["x"] += 1

George





More information about the Python-list mailing list