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'}
还是我得自己做?
发布于 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
发布于 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))
发布于 2019-05-05 05:31:35
连接到SQLite:con = sqlite3.connect(.....)
之后,只需运行:
con.row_factory = sqlite3.Row
瞧!
https://stackoverflow.com/questions/3300464
复制相似问题