Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can simply call the .as_dict() method on the row element to transform it into a dictionary. Here's an example:

from sqlalchemy import create_engine, MetaData, Table

engine = create_engine('sqlite:///example.db')
metadata = MetaData()

# define your table
my_table = Table('my_table', metadata, autoload=True, autoload_with=engine)

# execute a query and get a row element
query = my_table.select().where(my_table.c.id == 1)
row = engine.execute(query).fetchone()

# transform the row element into a dictionary
row_dict = row._asdict()

print(row_dict)

In this example, we defined a table called my_table and executed a query to fetch a row where the id column is equal to 1. Then, we transformed the row element into a dictionary using the _asdict() method and stored it in a variable called row_dict. Finally, we printed the contents of the dictionary.

Note that the _asdict() method will return an OrderedDict, which is like a regular dictionary but with an order preserving the order of the columns in the result set.