Welcome, guest | Sign In | My Account | Store | Cart

this dictionary allows easy manual creation of nested hierarchies, like so:

window.style.width=5

or...

window['background-color'].rgb= 255,255,255

Python, 13 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class easyaccessdict(dict):
    def __getattr__(self,name):
        if name in self:
            return self[name]
        n=easyaccessdict()
        super().__setitem__(name, n)
        return n
    def __getitem__(self,name):
        if name not in self:
            super().__setitem__(name,nicedict())
        return super().__getitem__(name)
    def __setattr__(self,name,value):
        super().__setitem__(name,value)

By example:

>>> d= easyaccessdict()
>>> d
{}
>>> d.foo.bar= 'a'
>>> d
{'foo':{'bar':'a'}}
>>> d['foo']
{'bar':'a'}
>>> d['foo'].blah= 7
>>> d
{'foo':{'bar':'a', 'blah':7}}
>>> d.a.b.c.e.e.f.g.h= 11

etc.

1 comment

Nezar Abdennur 10 years, 8 months ago  # | flag

Note that you can make this even terser by implementing __missing__:

class easyaccessdict(dict):
    def __getattr__(self, name):
        return self[name]
    def __setattr__(self, name, value):
        super().__setitem__(name,value)
    def __missing__(self, name):
        super().__setitem__(name, easyaccessdict())
        return super().__getitem__(name)

Also, super should be called using super(easyaccessdict, self) for this to work in python 2.