Skip to content

Instantly share code, notes, and snippets.

@Ivlyth
Last active August 29, 2015 14:14
Show Gist options
  • Save Ivlyth/3c36caf243af2b3cd178 to your computer and use it in GitHub Desktop.
Save Ivlyth/3c36caf243af2b3cd178 to your computer and use it in GitHub Desktop.
Python Js styled dict
# copy from `https://github.com/damonchen/onion/blob/master/onion/utils/_dict.py`
# and `https://github.com/damonchen/onion/blob/master/onion/utils/tools.py`
class JsDict(dict):
def __getattr__(self, key):
try:
v = self[key]
except:
v = None
return v
def __setattr__(self, key, value):
self[key] = value
def list2jsdict(v):
result = [value2jsdict(t) for t in v]
if isinstance(v, tuple):
return tuple(result)
else:
return result
def dict2jsdict(v):
j = JsDict()
for key, value in v.iteritems():
j[key] = value2jsdict(value)
return j
def value2jsdict(v):
if isinstance(v, (tuple, list)):
return list2jsdict(v)
elif isinstance(v, dict):
return dict2jsdict(v)
else:
return v
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment