Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a python `dict` to a `sqlalchemy.engine.row`

I know we can convert a sqlalchemy.engine.row into a dict by row_dict = dict(row). Is it possible to do the reverse, i.e. something like row = Row(row_dict)? I tried it, but not working, with an error as *** TypeError: BaseRow expected 5 arguments, got 1

like image 544
Quan Zhou Avatar asked Apr 01 '26 21:04

Quan Zhou


1 Answers

At the very least you could do

import sqlalchemy as sa

engine = sa.create_engine("sqlite:///:memory:")

# test data
data = {"col1": "foo", "col2": "bar"}

sql = "SELECT " + ", ".join([f":{k} as {k}" for k in data])
print(sql)  # SELECT :col1 as col1, :col2 as col2

with engine.begin() as conn:
    row = conn.execute(sa.text(sql), data).fetchone()

print(type(row))  # <class 'sqlalchemy.engine.row.LegacyRow'>
print(row)  # ('foo', 'bar')
print(row.col1)  # foo
like image 142
Gord Thompson Avatar answered Apr 04 '26 10:04

Gord Thompson