python-3.x - 创建多个字典时,分块列表抛出“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
解决方案
我通过立即制作字典解决了这个问题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.')
推荐阅读
- oracle - 如何结合使用 Oracle 云基础设施 MYSQL DB 和 XDev API?
- postgresql - ts_rank 什么时候返回值 1
- java - 为什么我的程序在 main 中调用时不接受方法中的 int[] 参数?
- mbaas - 第一次在appwrite mbaas中如何注册?
- angular - 403错误没有被catchError函数Angular 7捕获
- apache-kafka - Kafka:sendOffsetsToTransaction 与多个消费者
- angular - Angular 2中带有类型或模型的简单发布请求
- java - 为什么无法通知依赖解析侦听器错误出现在颤动中?
- javascript - javascript条件语句中的错误
- javascript - 在这个片段中 [direction] 是什么意思