如何从sqlite查询中获取dict?

2021-12-08 00:00:00 python dictionary sql dataformat sqlite
db = sqlite.connect("test.sqlite")
res = db.execute("select * from table")

通过迭代,我得到与行对应的列表.

With iteration I get lists coresponding to the rows.

for row in res:
    print row

我可以得到列的名称

col_name_list = [tuple[0] for tuple in res.description]

但是是否有一些函数或设置可以获取字典而不是列表?

But is there some function or setting to get dictionaries instead of list?

{'col1': 'value', 'col2': 'value'}

还是我必须自己做?

推荐答案

你可以使用 row_factory,如文档中的示例:

You could use row_factory, as in the example in the docs:

import sqlite3

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

con = sqlite3.connect(":memory:")
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print cur.fetchone()["a"]

或遵循文档中此示例之后给出的建议:

or follow the advice that's given right after this example in the docs:

如果返回一个元组还不够并且您希望基于名称访问列,您应该考虑设置row_factory 到高度优化的sqlite3.Row 类型.行同时提供基于索引且不区分大小写基于名称的列访问几乎没有内存开销.它会可能比你自己的好自定义基于字典的方法或甚至是基于 db_row 的解决方案.

If returning a tuple doesn’t suffice and you want name-based access to columns, you should consider setting row_factory to the highly-optimized sqlite3.Row type. Row provides both index-based and case-insensitive name-based access to columns with almost no memory overhead. It will probably be better than your own custom dictionary-based approach or even a db_row based solution.

这是第二种解决方案的代码:

Here is the code for this second solution:

con.row_factory = sqlite3.Row

相关文章