Skip to content

Instantly share code, notes, and snippets.

@sungitly
Last active November 15, 2023 21:04
Show Gist options
  • Save sungitly/3f75cb297572dace2937 to your computer and use it in GitHub Desktop.
Save sungitly/3f75cb297572dace2937 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__.iteritems()
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
@shyjuzz
Copy link

shyjuzz commented Feb 11, 2020

def obj_to_dict(obj):
    if type(obj) is dict:
        res = {}
        for k, v in obj.items():
            res[k] = obj_to_dict(v)
        return res
    elif type(obj) is list:
        return [obj_to_dict(item) for item in obj]
    elif type(obj) is SimpleNamespace:
        return obj_to_dict(vars(obj))
    else:
        return obj

@alpianon
Copy link

def convert2serialize(obj):
    if isinstance(obj, dict):
        return { k: convert2serialize(v) for k, v in obj.items() }
    elif hasattr(obj, "_ast"):
        return convert2serialize(obj._ast())
    elif not isinstance(obj, str) and hasattr(obj, "__iter__"):
        return [ convert2serialize(v) for v in obj ]
    elif hasattr(obj, "__dict__"):
        return {
            k: convert2serialize(v)
            for k, v in obj.__dict__.items()
            if not callable(v) and not k.startswith('_')
        }
    else:
        return obj

@ahancock1
Copy link

def to_dict(item):

    match item:
        case dict():
            data = {}
            for k, v in item.items():
                data[k] = to_dict(v)
            return data
        case list() | tuple():
            return [to_dict(x) for x in item]
        case object(__dict__=_):
            data = {}
            for k, v in item.__dict__.items():
                if not k.startswith("_"):
                    data[k] = to_dict(v)
            return data
        case _:
            return item

@thatrandomperson5
Copy link

@sungitly please support slotted objects

@andrei-korshikov
Copy link

@ahancock1 Your structural pattern matching rocks:D What about vars() and a dict comprehension?

case object(__dict__=_):
       data = {}
       for k, v in item.__dict__.items():
           if not k.startswith("_"):
               data[k] = to_dict(v)
       return data
return {key: to_dict(value) for key, value in vars(item).items()}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment