Python - mysqlDB,sqlite结果作为字典 [英] Python - mysqlDB, sqlite result as dictionary
问题描述
当我做某事像
sqlite.cursor.execute("SELECT * FROM foo")
result = sqlite.cursor.fetchone()
我想要记住这些列似乎是可以的顺序要获取它们,例如
I think have to remember the order the columns appear to be able to fetch them out, eg
result[0] is id
result[1] is first_name
所以我可以改为使用结果['id']或类似的?
is there a way to return a dictionary? so I can instead just use result['id'] or similar?
编号列的问题是,如果你编写代码,然后插入一个列,你可能有更改代码,例如first_name的result [1]现在可能是date_joined,所以必须更新所有代码...
The problem with the numbered columns is, if you write your code then insert a column you might have to change the code eg result[1] for first_name might now be a date_joined so would have to update all the code...
推荐答案
p> David Beazley在他的 Python Essential Reference 中有一个很好的例子。
我手头没有这本书,但我认为他的例子是这样的:
David Beazley has a nice example of this in his Python Essential Reference.
I don't have the book at hand, but I think his example is something like this:
def dict_gen(curs):
''' From Python Essential Reference by David Beazley
'''
import itertools
field_names = [d[0].lower() for d in curs.description]
while True:
rows = curs.fetchmany()
if not rows: return
for row in rows:
yield dict(itertools.izip(field_names, row))
样本使用情况:
>>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute('create table test (col1,col2)')
<sqlite3.Cursor object at 0x011A96A0>
>>> c.execute("insert into test values (1,'foo')")
<sqlite3.Cursor object at 0x011A96A0>
>>> c.execute("insert into test values (2,'bar')")
<sqlite3.Cursor object at 0x011A96A0>
# `dict_gen` function code here
>>> [r for r in dict_gen(c.execute('select * from test'))]
[{'col2': u'foo', 'col1': 1}, {'col2': u'bar', 'col1': 2}]
这篇关于Python - mysqlDB,sqlite结果作为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!