簡體   English   中英

在我的字典字典上設置默認值

[英]Set a default on my dictonary python

問題我只想從數據庫中獲取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 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'}]}

未經測試(不適合您的數據庫和連接器),但這是:

[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 ,在大多數db-api實現中,游標本身都是可迭代的-一個懶惰的游標,因此您可以避免只在內存中加載整個結果集( .fetchall()會發生這種情況)想遍歷它。 如果收到TypeError: XXX object is not iterable異常,則傳遞cursor.fetchall()而不是cursor (並與pyodbc維護人員聯系,要求他們使cursor變為可迭代)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM