0

I'm executing a raw query with SQLAlchemy. Is there a way to get the rows returned as dicts that contain column names (equivalent of DictCursor in MySQLdb) ? Code:

sql = 'select * from table'

rows = engine.execute(text(sql))

for row in rows:
    print row
Chris Koston
  • 975
  • 2
  • 9
  • 22
  • 1
    I'm not sure I understand the question. From this : http://docs.sqlalchemy.org/en/latest/core/connections.html#basic-usage it looks like it's already returning a row "dict"-like structure. Maybe you could try row.__dict__ to print the content [(1)](http://stackoverflow.com/a/10370224/154607). – Cedric Feb 14 '17 at 23:11
  • Ha, indeed. The object returned implements the __getitem__ operator. The default conversion to str is just a list format. Excellent, thanks for the answer! – Chris Koston Feb 15 '17 at 02:58
  • Does this answer your question? [python sqlalchemy get column names dynamically?](https://stackoverflow.com/questions/8947616/python-sqlalchemy-get-column-names-dynamically) – snakecharmerb Aug 28 '22 at 17:46

2 Answers2

1

this worked for me:

     sql = 'select * from table'

     rows = engine.execute(text(sql))
     columns = None
     for row in rows:
         if columns is None:
             columns = row.keys()
         print(dict(zip(columns, row)))
azuer88
  • 73
  • 8
-1

I think you could use some parser like this bellow. In this case will return a list with dicts inside, but you can change it to fit your needs.

def result_cursor_to_list(rows):
    data = []
    info = rows.keys()
    for row in rows:
        line = {}
        for i, col in enumerate(row):
            line[info[i]] = col
        data.append(line)
    return data
Everton Castro
  • 129
  • 1
  • 8