Dictionary that adds items to itself

Quinn Dunkan quinn at pfennig.ugcs.caltech.edu
Tue Apr 30 18:09:35 EDT 2002


On 25 Apr 2002 09:09:27 -0700, gyromagnetic <gyromagnetic at excite.com> wrote:
>Hi,
>I would appreciate some advice on the following. I would like to
>create a dictionary-like object with the same properties as a normal
>dictionary except with regard to adding items. When items are added, I
>would like them to be processed by a function that may generate
>additional items. I would like these additional items to be added to
>the dictionary, have the function applied to them, have the resulting
>items added to the dictionary, etc.

Off the top of my head:

import UserDict
class Apply_dict(UserDict.UserDict):
    def __init__(self, mapf):
        self.mapf = mapf
        UserDict.UserDict.__init__(self)
    def __setitem__(self, k, v):
        v, extras = self.mapf(k, v)
        self.data[k] = v
        for k, v in extras:
            self[k] = v

Just make sure mapf() doesn't generate extras that eventually generate the
original input or it'll loop.



More information about the Python-list mailing list