how to create a dictionary out of a join from sqlalchemy to python

Viewed 158

I am using python and SQLAlchemy

After joining two tables and used a _asdict() to create an array of dictionary out of the result, i am facing the data below and trying to find a good way to create a single dictionary out of it.

data from query

data = [{'User': <app.data_access.models.User object at 0x7fcb, 'Products': <app.data_access.models.Availability object at 0x7fcb>}
{'User': <app.data_access.models.User object at 0x7fcb>, 'Products': <app.data_access.models.Products object at 0x7fcb>}]

The object User table has the same data for the two instances with the fields: first_name, "last_name" only but Products instances are have different in terms of data.

Below is the data structure that i am trying to create as a result:

result expected

dic = {
  "first_name": "xyz",
  "last_name": "zba"
  "products": [{"all the fields of Products instance 1"}, {"all the fields of Products instance 2"}
}

I am running out of ideas, everything I tried have failed.

example:

result = {}

for data in some_query:
  for key, value in data.items():
     if key == "Products":
        response["products"] = [value]
     elif key == "User":
        response.update(value)

print(result)

How can i possibly create dictionary as a result using python from the query above?

Any help would be much appreciated

0 Answers
Related