То, как я делал это в прошлом:
def dict_factory(cursor, row):
d = {}
for idx,col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
Затем вы настраиваете это в своем соединении:
from pysqlite2 import dbapi2 as sqlite
conn = sqlite.connect(...)
conn.row_factory = dict_factory
Это работает в pysqlite-2.4.1 и python 2.5.4.
I know you're not asking this, but why not just use sqlalchemy to build an orm for the database? then you can do things like,
entry = model.Session.query(model.Votes).first()
print entry.bill, entry.senator_id, entry.vote
as an added bonus your code will be easily portable to an alternative database, and connections and whatnot will be managed for free.
Конечно, создайте себя как DictConnection и DictCursor, как описано и показано на http://trac.edgewall.org/pysqlite.org-mirror/wiki/PysqliteFactories , например .
На самом деле в sqlite3 есть опция для этого. Измените член row_factory
объекта подключения на sqlite3.Row
:
conn = sqlite3.connect('db', row_factory=sqlite3.Row)
или
conn.row_factory = sqlite3.Row
. Это позволит вам получить доступ к элементам строки по имени - в стиле словаря - или по индексу. Это намного эффективнее, чем создание собственного обходного пути.