Python – mysqlDB,sqlite結果作為字典
當我做某事時
sqlite.cursor.execute("SELECT * FROM foo") result = sqlite.cursor.fetchone()
我想必須記住這些列似乎能夠把它們取出來的順序,例如
result[0] is id result[1] is first_name
有沒有辦法返回字典?所以我可以使用結果[‘id’]或類似的?
編號列的問題是,如果您編寫程式碼,則插入一列,您可能需要更改程式碼,例如first_name的result [1]現在可能是date_joined,因此必須更新所有程式碼…
David Beazley在他的Python Essential Reference中有一個很好的例子.
我手上沒有這本書,但我認為他的例子是這樣的:
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}]
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/4147707/python-mysqldb-sqlite-result-as-dictionary