Convert sqlalchemy row object to python dict
You may access the internal __dict__
of a SQLAlchemy object, like the following::
for u in session.query(User).all():
print u.__dict__
I couldn't get a good answer so I use this:
def row2dict(row):
d = {}
for column in row.__table__.columns:
d[column.name] = str(getattr(row, column.name))
return d
Edit: if above function is too long and not suited for some tastes here is a one liner (python 2.7+)
row2dict = lambda r: {c.name: str(getattr(r, c.name)) for c in r.__table__.columns}
As per @zzzeek in comments:
note that this is the correct answer for modern versions of SQLAlchemy, assuming "row" is a core row object, not an ORM-mapped instance.
for row in resultproxy:
row_as_dict = dict(row)