如何从sqlite查询中获取dict?

How can I get dict from sqlite query?(如何从sqlite查询中获取dict?)
本文介绍了如何从sqlite查询中获取dict?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于如何从sqlite查询中获取dict?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)