0 votes
in Education by (1.7m points)
object looks like as below

{

"id":1,

"image":"path/to/image",

"employee_data":<sql_alcahmy_object>,

}

again sql_alcahmy_object is as below

{

"employee_previous":<sql_alchemy_object2>,

"employee_salary":"1$",

}

again sql_alcahmy_object2 is as below

{"company":"xyz","years":10}

below method will be used to extract all data from sql alchemy object

sql_alchemy_object.__dict__

below is the recursive method planned but it didn't work out

def extract_recursive(deepvalue,alldata={}):

    for eachkey,eachvalue in deepvalue.__dict__.iteritems():

        if hasattr(eachvalue,"__dict__"):

            alldata.update({eachkey:extract_recursive(eachvalue)})

        else:   

            alldata.update({eachkey:eachvalue})

    print(alldata)

expected output

{

"id":1,

"image":"path/to/image",

"employee_data":{

             "employee_previous":{"company":"xyz","years":10},

             "employee_salary":"1$",

              }

}

Available methods in deepvalue and sql_alcahmy_object as below

 ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__mapper__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__table__', '__tablename__', '__weakref__', '_decl_class_registry', '_sa_class_manager', 'age']

JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)

1 Answer

0 votes
by (1.7m points)
There is a misunderstanding of what is __dict__ here

It actually is

A dictionary or other mapping object used to store an object’s (writable) attributes.

but it does not allow to access nested dicts of a dict.

So, if you want to iterate over items in a dict, you just have to call thedict.iteritems() not thedict.__dict__.iteritems().

Then, if you want to check if variable contains a dict instance, use isinstance(a_dict, dict), not hasattr(a_dict, '__dict__').

Additionaly, using a mutable object as a default value for a function argument can produce non-intuitive result and is strongly discouraged (see "Least Astonishment" and the Mutable Default Argument) Instead you should probably pass None as default value and add a alldata = alldata or {} at the begining of your function.

Finally, although I do not understand the point of your function, this version should work better:

def extract_recursive(deepvalue, alldata=None):

    alldata = alldata or {}

    for eachkey, eachvalue in deepvalue.iteritems():

        if isinstance(eachvalue, dict):

            alldata.update({eachkey:extract_recursive(eachvalue)})

        else:

            alldata.update({eachkey:eachvalue})

    print(alldata)
...