zhengxiaowai
8/15/2017 - 8:36 AM

magicdict.py

class MagicDict(object):
    def __init__(self, default=None):
        if isinstance(default, (type(None), type(dict))):
            raise TypeError('default must dict or None')
                                   
        self.store = {}
        if default is not  None:
            for k, v in default.items():
                self.set(k, v)
    
    def __str__(self):
        return '%s' % str(self.store)
    
    def __repr__(self):
        return "MagicDict(%s)" % str(self.store)
    
    @property    
    def json(self):
        return self.store

    def get(self, key):
        layers = key.split('.')
        value = self.store
        for item in layers:
            value = value[item]
        return value

    def set(self, key, value):
        key_parts = key.split('.')
        store = self.store
        while key_parts[:-1]:
            key = key_parts.pop(0)
            if key not in store:
                store[key] = {}
            store = store[key]

        store[key_parts[-1]] = value