cool things you can do with dict

alex goretoy aleksandr.goretoy at gmail.com
Mon Mar 16 23:40:46 EDT 2009


I though this was cool so I'd post about it, its one of the recipes

class peanutsdict(dict):
    def __init__(self,default=None):
        dict.__init__(self)
        self.default = default

    def __getitem__(self,key):
        if key in self:
            return dict.__getitem__(self,key)
        else:

            return self.default

    def get(self, key, *args):
        if not args:
            args = (self.default,)
        return dict.get(self, key, *args)

    def merge(self, other):
        for key in other:
            if key not in self:
                self[key] = other[key]

a=peanutsdict()
a.b=peanutsdict()
a.b.c=peanutsdict()
a.x=1
a.b.y=2
a.b.c.z=3

>>> print a
{}
>>> print a.__dict__
{'default': None, 'x': 1, 'b': {}}
>>> print a.b.__dict__
{'default': None, 'y': 2, 'c': {}}
>>> print a.b.c.__dict__
{'default': None, 'z': 3}
>>> print a.b.c.z
3
>>> print a.b.c
{}
>>> a.b.b=peanutsdict()
>>> class pdict(dict): pass
...
>>> a.b.b.a=pdict()
>>> a.b.b
{}
>>> a.b.b.__dict__
{'default': None, 'a': {}}
>>> a.b.b.__dict__['a']
{}
>>> a.b.b.__dict__['a'].x=4
>>> a.b.b.__dict__['a'].x
4
>>> a.b.b.a.x
4

Anyone else know anymore cool pieces of code?


-Alex Goretoy
http://www.goretoy.com

Jean Anouilh  - "What you get free costs too much."
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090316/5bc54839/attachment.html>


More information about the Python-list mailing list