How to convert SQLAlchemy row object to a Python 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}
How to convert SQLAlchemy row object to a Python 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}
Return SQLAlchemy results as dicts instead of lists
The results look like tuples/lists, but they are actually a special Row
object (KeyedTuple
for SQLAlchemy < 1.4). Use the _asdict()
method to convert each row to a dict.
return [r._asdict() for r in results]
[{'campaign_id': 3, 'title': 'campaign title', 'status_count': 1},
{'campaign_id': 4, 'title': 'campaign title', 'status_count': 1}]
convert sqlalchemy query result to a list of dicts
Try
result_dict = [u.__dict__ for u in my_query.all()]
Besides what is the type of your result_dict
before the for
loop? Its behavior is rather strange.
Convert SqlAlchemy orm result to dict
You can use the relationships property of the mapper. The code choices depend on how you want to map your data and how your relationships look. If you have a lot of recursive relationships, you may want to use a max_depth counter. My example below uses a set of relationships to prevent a recursive loop. You could eliminate the recursion entirely if you only plan to go down one in depth, but you did say "and so on".
def object_to_dict(obj, found=None):
if found is None:
found = set()
mapper = class_mapper(obj.__class__)
columns = [column.key for column in mapper.columns]
get_key_value = lambda c: (c, getattr(obj, c).isoformat()) if isinstance(getattr(obj, c), datetime) else (c, getattr(obj, c))
out = dict(map(get_key_value, columns))
for name, relation in mapper.relationships.items():
if relation not in found:
found.add(relation)
related_obj = getattr(obj, name)
if related_obj is not None:
if relation.uselist:
out[name] = [object_to_dict(child, found) for child in related_obj]
else:
out[name] = object_to_dict(related_obj, found)
return out
Also, be aware that there are performance issues to consider. You may want to use options such as joinedload or subqueryload in order to prevent executing an excessive number of SQL queries.
How to convert SQLAlchemy row object to a Python 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}
How can I build a dictionary from a SQLAlchemy row, using cell data as keys and values instead of column names?
dict = {result.meta_key: result.meta_value for result in results}
It was much easier than I thought it was.
Related Topics
Find Common Substring Between Two Strings
Can You Monkey Patch Methods on Core Types in Python
Why Does (1 in [1,0] == True) Evaluate to False
What Does 'Weight' Do in Tkinter
How to Extract Multiple JSON Objects from One File
Error "Filename.Whl Is Not a Supported Wheel on This Platform"
Pandas Groupby: How to Get a Union of Strings
Python Garbage Collector Documentation
How to Capture Stdout Output from a Python Function Call
How to Use a Dll File from Python
What Are "First-Class" Objects
How to Remove \Xa0 from String in Python
Rotate Axis Text in Python Matplotlib
How to Filter Query Objects by Date Range in Django
Catch a Thread's Exception in the Caller Thread
Compare Object Instances for Equality by Their Attributes
Removing Item from List - During Iteration - What's Wrong with This Idiom