Skip to main content

Command Palette

Search for a command to run...

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

Published
1 min read
Y

never give up!

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

More from this blog

Y

Yuanfei

7 posts