MFB MFB - 5 months ago 7
Python Question

What is the most economical way to convert nested Python objects to dictionaries?

I have some SQLAlchemy objects which contain lists of more SQLAlchemy objects, and so on (for about 5 levels). I wish to convert all the objects to dictionaries.

I can convert an object to a dictionary by using the

__dict__
property, no problem. However, I'm having trouble figuring out the best way to convert all the nested objects as well, without having to do each level explicitly.

So far, this is the best I can come up with, but it doesn't recurse properly. It basically breaks after one pass, so there's clearly something wrong with my logic. Can you see what's wrong with it??

I am hoping to do:

all_dict = myDict(obj.__dict__)

def myDict(d):
for k,v in d.items():
if isinstance(v,list):
d[k] = [myDict(i.__dict__) for i in v]
else:
d[k] = v
return d

Answer

I am not sure if I understood exactly what you want - but if I got, this function can do what you want: It does search recursively on an object's attributes, yielding a nested dictionary + list structure, with the ending points being python objects not having a __dict__ attribute - which in SQLAlchemy's case are likely to be basic Python types like numbers and strings. (If that fails, replacing the "hasattr dict" test for soemthing more sensible should fix the code for your needs.

def my_dict(obj):
    if not  hasattr(obj,"__dict__"):
        return obj
    result = {}
    for key, val in obj.__dict__.items():
        if key.startswith("_"):
            continue
        element = []
        if isinstance(val, list):
            for item in val:
                element.append(my_dict(item))
        else:
            element = my_dict(val)
        result[key] = element
    return result