Skip to main content

A method to convert python object to dict(supporting recursion)

Published 1 min readMarkdown

Code

def object2Map(obj:object):
    """covert object to dict"""
    m = obj.__dict__
    for k in m.keys():
        v = m[k]
        if hasattr(v, "__dict__"):
            m[k] = object2Map(v)
    return m

Test

class Test:
    def __init__(self):
        self.a = 1
        self.b = 2

test = Test()
test.c = Test()
print(object2Map(test))

results: result pitcture

About the author

No comments yet. Be the first to comment.

More from this blog