dictionary wart

Skip Montanaro skip at pobox.com
Thu Mar 18 10:15:58 EST 2004


    Jesper> For instance in a dictionary which is mapping strings to
    Jesper> integers (or lists), I would like to do

    Jesper> a[my_key]+=5

    Jesper> expressing that with get() would be awkward.

Though not *terribly* awkward:

    a[my_key] = a.get(my_key, 0) + 5

I agree it's a bit clumsy, but I think it's the best you can do if you don't
want to subclass dict (I don't really like {}.setdefault()):

    class ddict(dict):
        def __init__(self, default=None, init=True):
            self.default = default
            self.init = init

        def __getitem__(self, key):
            if key in self:
                return self.get(key)
            else:
                if self.init:
                    self[key] = self.default
                return self.default

    d = ddict(default="Jesper", init=False)
    print "abc" in d
    print d["abc"]
    d = ddict(default=0)
    d["abc"] += 5
    print d["abc"]

I suspect there's more to it than I've implemented, but that should get you
pointed in the right direction.

Skip




More information about the Python-list mailing list