首页 > 解决方案 > 创建多个字典时,分块列表抛出“zip 参数 #2 必须支持迭代”

问题描述

我在将分块列表转换为多个字典以便批量发送我的请求时遇到问题:

fd = open(filename, 'r')
sqlFile = fd.read()
fd.close()
commands = sqlFile.split(';')
for command in commands:
    try:
        c = conn.cursor()
        c.execute(command)

        // create a list with the query results with batches of size 100
        for batch in grouper(c.fetchall(),100):
            // This is where the error occurs:
            result = [dict(zip([key[0] for key in c.description], i)) for i in batch]
            # TODO: Send the json with 100 items to API
        
    except RuntimeError:
        print('Error.') 

问题是它只遍历批次一次并给出以下错误。实际上,行数是 167。所以在第一个请求中应该有 100 个要发送的项目的结果,而第二次迭代应该在第二个请求中包含要发送的 67 个项目。

TypeError: zip argument #2 must support iteration

标签: python-3.xlistitertools

解决方案


我通过立即制作字典解决了这个问题c.rowfactory = makeDictFactory(c)

def makeDictFactory(cursor):
columnNames = [d[0] for d in cursor.description]
def createRow(*args):
    return dict(zip(columnNames, args))
return createRow

def getAndConvertDataFromDatabase:(filename)
fd = open(filename, 'r')
sqlFile = fd.read()
fd.close()
commands = sqlFile.split(';')
for command in commands:
    try:
        c = conn.cursor()
        c.execute(command)
        c.rowfactory = makeDictFactory(c)
        data = c.fetchall()
        for batch in [data[x:x+100] for x in range(0, len(data), 100)]:
        return postBody(json.dumps(batch,default = myconverter), dataList[filename])
    except RuntimeError:
        print('Error.')      

推荐阅读