How to convert SQLAlchemy row object to a Python dict?

How to convert SQLAlchemy row object to a 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 couldnt 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}

How to convert SQLAlchemy row object to a Python dict?

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)

Leave a Reply

Your email address will not be published. Required fields are marked *