内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/4147707/python-mysqldb-sqlite-result-as-dictionary
当我做某事时
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
以上所述就是小编给大家介绍的《Python – mysqlDB,sqlite结果作为字典》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- Swift 中如何使用字典类型作为范型约束
- 【Python—字典的用法】创建字典的3种方法
- Python 字典(Dictionary)
- python 数据类型 ----字典
- map字典
- golang 字典map
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
程序员2010精华本
程序员杂志社 / 电子工业 / 2011-1 / 49.00元
《程序员(2010精华本)》主要内容:《程序员》创刊10年来,每年末编辑部精心打造的“合订本”已经形成一个品牌,得到广大读者的认可和喜爱。今年,《程序员》杂志内容再次进行了优化整合,除了每期推出的一个大型专题策划,各版块也纷纷以专题、策划的形式,将每月的重点进行了整合,让内容非常具有凝聚力,如专题篇、人物篇、实践篇等。另外杂志的版式、色彩方面也有了很大的飞跃,给读者带来耳目一新的阅读体验。一起来看看 《程序员2010精华本》 这本书的介绍吧!