在我的dictonary python上设置默认值

时间:2017-06-22 13:43:32

标签: python python-2.7

问题我只想从我的数据库中获取我的view_id列,但是我希望我的第一个键有一些序列号。以下是我到目前为止的任何帮助将不胜感激!

如果我尝试将count设置为第一个键,这会给我一个语法错误:

' '

我也试过这个,但是我收到了一个新错误: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 element #0 has length 3; 2 is required

以下是现在的样子

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'}]}

1 个答案:

答案 0 :(得分:0)

未经过测试(不是使用您的数据库和连接器),但是:

[dict(count=str(index), view_id=row[0]) for index, row in enumerate(cursor, 1)]

应符合您的预期结果。

来自doc:

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]), ...

请注意,我直接传递cursor,在大多数db-api实现中,游标本身是一个可迭代的 - 一个懒惰的,所以你可以避免将整个结果集加载到内存中(这就是发生的事情)使用.fetchall())当你只想迭代它时。如果您收到TypeError: XXX object is not iterable例外,则传递cursor.fetchall()而不是cursor(并与pyodbc维护人员联系,要求他们使cursor可迭代)。