Python 为我的听写设置默认值
问题我只想从我的数据库中获取我的view\u id列,但是我想要一些序列号作为我的第一个键。以下是我迄今为止所做的一切,如有任何帮助,将不胜感激 如果尝试将count设置为第一个键,则会出现语法错误:Python 为我的听写设置默认值,python,python-2.7,Python,Python 2.7,问题我只想从我的数据库中获取我的view\u id列,但是我想要一些序列号作为我的第一个键。以下是我迄今为止所做的一切,如有任何帮助,将不胜感激 如果尝试将count设置为第一个键,则会出现语法错误: import pyodbc class ShopView(object): def getViews(self): conn = pyodbc.connect(r'DSN=mydb;UID=test;PWD=xxxxxxxxxxxxx') sql = "SELECT DIS
import pyodbc
class ShopView(object):
def getViews(self):
conn = pyodbc.connect(r'DSN=mydb;UID=test;PWD=xxxxxxxxxxxxx')
sql = "SELECT DISTINCT view_id FROM [TEST].[dbo].[SHOP_VIEW]"
cursor = conn.cursor()
cursor.execute(sql)
count = 0
try:
return {'shop_views':
[dict(zip(count += 1, [column[0] for column in cursor.description], row))
for row in cursor.fetchall()]}
finally:
cursor.close()
conn.close()
我也尝试了这个,但我得到了一个新错误:ValueError:dictionary update sequence元素#0的长度为3;2是必需的
try:
return {'shop_views':
[dict(zip([data[0] for data in str(cursor.rowcount)], [column[0] for column in cursor.description], row))
for row in cursor.fetchall()]}
finally:
cursor.close()
conn.close()
这是它现在的样子
{'shop_views': [{'view_id': 'ACTOB'}, {'view_id': 'BANDDIES'}, {'view_id': 'SpareNCLathe'}]}
以下是我希望它的外观:
{'shop_views': [{'count': '1', 'view_id': 'ACTOB'}{'count': '2', 'view_id': 'BANDDIES'}, {'count': '3', 'view_id': 'SpareNCLathe'}]}
未测试(不适用于您的db和连接器),但:
[dict(count=str(index), view_id=row[0]) for index, row in enumerate(cursor, 1)]
应该符合你的预期结果
从文档:
class enumerate(object)
| enumerate(iterable[, start]) -> iterator for index, value of iterable
|
| Return an enumerate object. iterable must be another object that supports
| iteration. The enumerate object yields pairs containing a count (from
| start, which defaults to zero) and a value yielded by the iterable argument.
| enumerate is useful for obtaining an indexed list:
| (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
请注意,我直接传递
游标
,在大多数db api实现中,游标本身是一个iterable-一个惰性游标,因此当您只想在其上迭代时,可以避免将整个结果集加载到内存中(这是.fetchall()
所发生的情况)。如果出现TypeError:XXX对象不可iterable
异常,则传递cursor.fetchall()
而不是cursor
(并联系pyodbc维护人员,要求他们使cursor
可iterable)。太棒了,你说得对了,非常感谢@布鲁诺·德舒利尔也感谢你的解释,我会毫不犹豫地记住这一点。