在我的字典python中设置默认值

2024-04-24 18:46:03 发布

您现在位置:Python中文网/ 问答频道 /正文

问题我只想从我的数据库中获取我的view\u 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'}]}

下面是我想要的样子:

{'shop_views': [{'count': '1', 'view_id': 'ACTOB'}{'count': '2', 'view_id': 'BANDDIES'}, {'count': '3', 'view_id': 'SpareNCLathe'}]}

Tags: inviewidforclosesqlcountcolumn
1条回答
网友
1楼 · 发布于 2024-04-24 18:46:03

未测试(不适用于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]), ...

请注意,我是直接传递cursor,在大多数dbapi实现中,游标本身就是一个iterable—一个惰性的游标,因此当您只想在.fetchall()上迭代时,可以避免将整个resultset加载到内存中(这就是.fetchall())。如果得到TypeError: XXX object is not iterable异常,则传递cursor.fetchall()而不是cursor(并联系pyodbc维护人员,让他们使cursor可编辑)。你知道吗

相关问题 更多 >