Created
August 15, 2017 08:36
-
-
Save zhengxiaowai/0b607da71a7ce33a857c2c7c7d0087bb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment