Python SQLAlchemy 将 SELECT 查询结果转换为字典列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19406859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:40:06  来源:igfitidea点击:

SQLAlchemy convert SELECT query result to a list of dicts

pythonsqlalchemy

提问by salamey

When I was using session.query, I was able to convert the result to a list of dicts :

当我使用 session.query 时,我能够将结果转换为 dicts 列表:

my_query = session.query(table1,table2).filter(all_filters)
result_dict = [u.__dict__ for u in my_query.all()]

But now that I have to work with the SELECT()operation, how can I convert the results to a dict that looks like, for every row result :

但是现在我必须使用该SELECT()操作,对于每一行结果,我如何将结果转换为看起来像这样的字典:

[{'Row1column1Name' : 'Row1olumn1Value', 'Row1column2Name' :'Row1Column2Value'},{'Row2column1Name' : 'Row2olumn1Value', 'Row2column2Name' : 'Row2Column2Value'},etc....].

[{'Row1column1Name' : 'Row1olumn1Value', 'Row1column2Name' :'Row1Column2Value'},{'Row2column1Name' : 'Row2olumn1Value', 'Row2column2Name' : 'Row2Column2Value'},etc....].

This is my SELECT() code :

这是我的 SELECT() 代码:

select = select([table1,table2]).where(all_filters)
res = conn.execute(select)
row = res.fetchone() #I have to use fetchone() because the query returns lots of rows
resultset=[]
while row is not None:
    row = res.fetchone()
    resultset.append(row)

print resultset

The result is :

结果是:

[('value1', 'value2', 'value3', 'value4'),(.....),etc for each row]

I'm new to Python, any help would be appreciated.

我是 Python 新手,任何帮助将不胜感激。

回答by fanti

This seems to be a RowProxy object. Try:

这似乎是一个 RowProxy 对象。尝试:

row = dict(zip(row.keys(), row))

回答by Carl

You can typecast each row from a select result as either a dict or a tuple. What you've been seeing is the default behaviour, which is to represent the each row as a tuple. To typecast to a dict, modify your code like this:

您可以将选择结果中的每一行类型转换为字典或元组。您所看到的是默认行为,即将每一行表示为一个元组。要将类型转换为 dict,请像这样修改您的代码:

select = select([table1, table2]).where(all_filters)
res = conn.execute(select)
resultset = []
for row in res:
    resultset.append(dict(row))
print resultset

This works nicely if you need to process the result one row at a time.

如果您需要一次处理一行结果,这很有效。

If you're happy to put all rows into a list in one go, list comprehension is a bit neater:

如果您很乐意一次性将所有行放入一个列表中,那么列表理解会更简洁一些:

select = select([table1, table2]).where(all_filters)
res = conn.execute(select)
resultset = [dict(row) for row in res]
print resultset

回答by Hymanotonye

For the first query its better to use this approach for sqlalchemy KeyedTuple:

对于第一个查询,最好将这种方法用于 sqlalchemy KeyedTuple:

# Convert an instance of `sqlalchemy.util._collections.KeyedTuple`
# to a dictionary
my_query = session.query(table1,table2).filter(all_filters)
result_dict = map(lambda q: q._asdict(), my_query)

OR

或者

result_dict = map(lambda obj: dict(zip(obj.keys(), obj)), my_query)

For ResultProxy as earlier mentioned:

对于前面提到的 ResultProxy:

result_dict = dict(zip(row.keys(), row))

回答by Nick Throckmorton

Building off of Fanti's answer, if you use a List Comprehension, you can produce the list of dicts all in one row. Here resultsis the result of my query.

根据 Fanti 的答案,如果您使用 List Comprehension,则可以在一行中生成所有 dicts 列表。这results是我的查询结果。

records = [dict(zip(row.keys(), row)) for row in results]