Skip to content

Instantly share code, notes, and snippets.

@Lu-Yi-Hsun
Forked from sungitly/todict.py
Created March 9, 2019 12:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lu-Yi-Hsun/0a134c74d3e6a1200066f70dffcabcba to your computer and use it in GitHub Desktop.
Save Lu-Yi-Hsun/0a134c74d3e6a1200066f70dffcabcba to your computer and use it in GitHub Desktop.
convert python object recursively to dict
def todict(obj, classkey=None):
if isinstance(obj, dict):
data = {}
for (k, v) in obj.items():
data[k] = todict(v, classkey)
return data
elif hasattr(obj, "_ast"):
return todict(obj._ast())
elif hasattr(obj, "__iter__"):
return [todict(v, classkey) for v in obj]
elif hasattr(obj, "__dict__"):
data = dict([(key, todict(value, classkey))
for key, value in obj.__dict__.items()
if not callable(value) and not key.startswith('_') and key not in ['name']])
if classkey is not None and hasattr(obj, "__class__"):
data[classkey] = obj.__class__.__name__
return data
else:
return obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment