如何从sqlite查询中获取字典?

186 投票
16 回答
183625 浏览
提问于 2025-04-16 01:37
db = sqlite.connect("test.sqlite")
res = db.execute("select * from table")

通过循环,我可以得到与行对应的列表。

for row in res:
    print row

我可以获取列的名称。

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

但是有没有什么函数或者设置可以让我得到字典,而不是列表呢?

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

还是说我得自己来做?

16 个回答

24

即使使用sqlite3.Row类,你仍然不能像这样使用字符串格式化:

print "%(id)i - %(name)s: %(value)s" % row

为了绕过这个问题,我使用了一个辅助函数,它将行数据转换成字典。只有在字典对象比Row对象更合适的时候我才会使用这个辅助函数(比如在字符串格式化时,因为Row对象本身不太支持字典的用法)。但在其他情况下,还是尽量使用Row对象。

def dict_from_row(row):
    return dict(zip(row.keys(), row))       
73

我想回答这个问题,虽然亚当·施米德格和亚历克斯·马特利的回答中已经部分提到过这个答案。这样像我一样有相同问题的人可以更容易找到答案。

conn = sqlite3.connect(":memory:")

#This is the important part, here we are setting row_factory property of
#connection object to sqlite3.Row(sqlite3.Row is an implementation of
#row_factory)
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute('select * from stocks')

result = c.fetchall()
#returns a list of dictionaries, each item in list(each dictionary)
#represents a row of the table
289

你可以使用 row_factory,就像文档中的例子那样:

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"]

或者你可以参考文档中这个例子后面给出的建议:

如果返回一个元组不够用, 而你想通过列名来访问数据, 那么你应该考虑把 row_factory 设置为高度优化的 sqlite3.Row 类型。 Row 允许你通过索引和不区分大小写的列名来访问数据, 几乎不会增加内存开销。 这可能比你自己写的基于字典的方法, 或者使用 db_row 的解决方案要好。

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

con = sqlite3.connect(…)
con.row_factory = sqlite3.Row   #   add this row
cursor = con.cursor()

撰写回答