python通过列名获取数组中的元素,就像在php中一样
我希望能够执行以下代码(即PHP): 在python中。因此,通过索引获取元素。最好的方法是什么?是的,使用内置类型python通过列名获取数组中的元素,就像在php中一样,php,python,arrays,Php,Python,Arrays,我希望能够执行以下代码(即PHP): 在python中。因此,通过索引获取元素。最好的方法是什么?是的,使用内置类型 d = {'name': 'user'} print d['name'] user 使用MySQLdb包中的DictCursor对象。这将在结果集中生成一个字典(映射),而不是通常的元组 import MySQLdb
d = {'name': 'user'}
print d['name']
user
使用MySQLdb包中的DictCursor对象。这将在结果集中生成一个字典(映射),而不是通常的元组
import MySQLdb
from MySQLdb import cursors
def fetchallmap(self, q, *args):
"""Fetch all rows into a dictionary.
"""
curs = self._connection.cursor(cursors.DictCursor)
curs.execute(q, args)
res = curs.fetchall()
curs.close()
self._connection.commit()
return res
这将返回字典(映射)列表。如果只需要一行,只需将fetchoone
替换为fetchall
def fetchonemap(self, q, *args):
"""Fetch one row into a dictionary.
"""
curs = self._connection.cursor(cursors.DictCursor)
curs.execute(q, args)
res = curs.fetchone()
curs.close()
self._connection.commit()
return res
使用Python字典,Python列表只能通过其索引进行访问。您是专门讨论SQL结果数组,还是一般数组?请使用以下内容:@georgesl我在谈论SQL结果,您能告诉我这在我的案例中是如何实际工作的吗?如何为每一行获取“name”和其他变量?下面是一个示例:发布为“answer”,这样我就可以接受它:))这很有效!谢谢。这似乎很有用。您能告诉我如何在实践中为每一行获取“name”变量吗?
def fetchonemap(self, q, *args):
"""Fetch one row into a dictionary.
"""
curs = self._connection.cursor(cursors.DictCursor)
curs.execute(q, args)
res = curs.fetchone()
curs.close()
self._connection.commit()
return res