首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从sqlite查询中获取dict?

如何从sqlite查询中获取dict?
EN

Stack Overflow用户
提问于 2010-07-21 22:42:21
回答 11查看 131.2K关注 0票数 146
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'}

还是我得自己做?

EN

回答 11

Stack Overflow用户

发布于 2017-01-29 19:04:55

我想我回答了这个问题,尽管亚当·施米德和亚历克斯·马尔泰利的答案都部分提到了这个问题。为了让其他像我一样有同样问题的人,很容易找到答案。

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
票数 57
EN

Stack Overflow用户

发布于 2012-03-03 02:20:00

即使使用sqlite3.Row类--您仍然不能使用以下形式的字符串格式:

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

为了解决这个问题,我使用了一个helper函数,该函数接受行并将其转换为字典。我只在dictionary对象比Row对象更可取时才使用它(例如,对于字符串格式化,Row对象本身也不支持dictionary )。但在其他时间都要使用Row对象。

def dict_from_row(row):
    return dict(zip(row.keys(), row))       
票数 22
EN

Stack Overflow用户

发布于 2019-05-05 05:31:35

连接到SQLite:con = sqlite3.connect(.....)之后,只需运行:

con.row_factory = sqlite3.Row

瞧!

票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3300464

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档