Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 266
MFB Avatar asked Nov 01 '11 07:11

MFB


People also ask

How do you convert an object to a dictionary in Python?

By using the __dict__ attribute on an object of a class and attaining the dictionary. All objects in Python have an attribute __dict__, which is a dictionary object containing all attributes defined for that object itself. The mapping of attributes with its values is done to generate a dictionary.

How do I convert a nested list to a dictionary?

Converting a Nested List to a Dictionary Using Dictionary Comprehension. We can convert a nested list to a dictionary by using dictionary comprehension. It will iterate through the list. It will take the item at index 0 as key and index 1 as value.

How do I convert nested dictionary to pandas DataFrame?

Converting a Nested Python Dictionary to a Pandas DataFrame We can simply pass in the nested dictionary into the DataFrame() constructor. However, Pandas will read the DataFrame with the keys as the indices.


2 Answers

Life Hack:

def to_dict(obj):
    return json.loads(json.dumps(obj, default=lambda o: o.__dict__))
like image 198
zachdb86 Avatar answered Sep 23 '22 15:09

zachdb86


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
like image 28
jsbueno Avatar answered Sep 25 '22 15:09

jsbueno