用查询结果填充字典
Populate a dictionary with the result of a query
我目前正在这样做:
cursor.execute('SELECT thing_id, thing_name FROM things')
things = [];
for row in cursor.fetchall():
things.append(dict([('thing_id',row[0]),
('thing_name',row[1])
]))
是否有一些 shorthand 我可以用来做这个,或者我应该写一些辅助函数吗?
things = [{'thing_id': row[0], 'thing_name': row[1]} for row in cursor.fetchall()]
或使用列表推导式 zip
:
things = [dict(zip(['thing_id', 'thing_name'], row)) for row in cursor.fetchall()]
如果使用Cursor.description
attribute,可以得到列名:
names = [d.name for d in c.description]
things = [dict(zip(names, row)) for row in cursor.fetchall()]
您可以使用 MySQLdb.cursors.DictCursor
class instead of MySQLdb.cursors.Cursor
by passing cursor class to cursor
方法:
In [9]: cur = conn.cursor(MySQLdb.cursors.DictCursor)
In [10]: cur.execute('SELECT * FROM test_table')
Out[10]: 3L
In [11]: cur.fetchall()
Out[11]:
({'create_time': datetime.datetime(2015, 12, 2, 10, 22, 23),
'id': 1L,
'name': 'Bob'},
{'create_time': datetime.datetime(2015, 12, 2, 10, 22, 34),
'id': 2L,
'name': 'Stive'},
{'create_time': datetime.datetime(2015, 12, 2, 10, 22, 37),
'id': 3L,
'name': 'Alex'})
我目前正在这样做:
cursor.execute('SELECT thing_id, thing_name FROM things')
things = [];
for row in cursor.fetchall():
things.append(dict([('thing_id',row[0]),
('thing_name',row[1])
]))
是否有一些 shorthand 我可以用来做这个,或者我应该写一些辅助函数吗?
things = [{'thing_id': row[0], 'thing_name': row[1]} for row in cursor.fetchall()]
或使用列表推导式 zip
:
things = [dict(zip(['thing_id', 'thing_name'], row)) for row in cursor.fetchall()]
如果使用Cursor.description
attribute,可以得到列名:
names = [d.name for d in c.description]
things = [dict(zip(names, row)) for row in cursor.fetchall()]
您可以使用 MySQLdb.cursors.DictCursor
class instead of MySQLdb.cursors.Cursor
by passing cursor class to cursor
方法:
In [9]: cur = conn.cursor(MySQLdb.cursors.DictCursor)
In [10]: cur.execute('SELECT * FROM test_table')
Out[10]: 3L
In [11]: cur.fetchall()
Out[11]:
({'create_time': datetime.datetime(2015, 12, 2, 10, 22, 23),
'id': 1L,
'name': 'Bob'},
{'create_time': datetime.datetime(2015, 12, 2, 10, 22, 34),
'id': 2L,
'name': 'Stive'},
{'create_time': datetime.datetime(2015, 12, 2, 10, 22, 37),
'id': 3L,
'name': 'Alex'})