When I was using session.query, I was able to convert the result to a list of dicts :
my_query = session.query(table1,table2).filter(all_filters)
result_dict = [u.__dict__ for u in my_query.all()]
But now that I have to work with the SELECT()
operation, how can I convert the results to a dict that looks like, for every row result :
[{'Row1column1Name' : 'Row1olumn1Value', 'Row1column2Name' :'Row1Column2Value'},{'Row2column1Name' : 'Row2olumn1Value', 'Row2column2Name' : 'Row2Column2Value'},etc....]
.
This is my SELECT() code :
select = select([table1,table2]).where(all_filters)
res = conn.execute(select)
row = res.fetchone() #I have to use fetchone() because the query returns lots of rows
resultset=[]
while row is not None:
row = res.fetchone()
resultset.append(row)
print resultset
The result is :
[('value1', 'value2', 'value3', 'value4'),(.....),etc for each row]
I'm new to Python, any help would be appreciated.
This seems to be a RowProxy object. Try:
row = dict(zip(row.keys(), row))
You can typecast each row from a select result as either a dict or a tuple. What you've been seeing is the default behaviour, which is to represent the each row as a tuple. To typecast to a dict, modify your code like this:
select = select([table1, table2]).where(all_filters)
res = conn.execute(select)
resultset = []
for row in res:
resultset.append(dict(row))
print resultset
This works nicely if you need to process the result one row at a time.
If you're happy to put all rows into a list in one go, list comprehension is a bit neater:
select = select([table1, table2]).where(all_filters)
res = conn.execute(select)
resultset = [dict(row) for row in res]
print resultset
Building off of Fanti's answer, if you use a List Comprehension, you can produce the list of dicts all in one row. Here results
is the result of my query.
records = [dict(zip(row.keys(), row)) for row in results]
For the first query its better to use this approach for sqlalchemy KeyedTuple:
# Convert an instance of `sqlalchemy.util._collections.KeyedTuple`
# to a dictionary
my_query = session.query(table1,table2).filter(all_filters)
result_dict = map(lambda q: q._asdict(), my_query)
OR
result_dict = map(lambda obj: dict(zip(obj.keys(), obj)), my_query)
For ResultProxy as earlier mentioned:
result_dict = dict(zip(row.keys(), row))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With