Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve python list of SQLAlchemy result set? [duplicate]

I have the following query to retrieve a single column of data:

routes_query = select(
    [schema.stop_times.c.route_number],
    schema.stop_times.c.stop_id == stop_id
).distinct(schema.stop_times.c.route_number)
result = conn.execute(routes_query)

return [r['route_number'] for r in result]

I am wondering if there is a cleaner way to retrieve a native list of the data rows returned.

like image 993
Gavin Schulz Avatar asked Nov 01 '12 19:11

Gavin Schulz


2 Answers

the most succinct way to pull out a list of 1-element tuples into a list is:

result = [r[0] for r in result]

or:

result = [r for r, in result]
like image 86
zzzeek Avatar answered Nov 11 '22 06:11

zzzeek


This is what I would use:

return zip(*result)[0]

It's more succinct that the the list comprehension methods in zzzeek's answer (22 characters rather than 29 or 31 characters), and for larger result sets the timings in this answer to a similar question show that it's faster too.

like image 25
markshep Avatar answered Nov 11 '22 08:11

markshep