在我的代码中,我使用以下代码创建了多个词典;
g = globals()
lrange = len(requestcells * 2)
for i in range(1, lrange):
g['request_{0}'.format(i)] = {}
然后我有一个for循环,它迭代列表中的excel坐标并从中提取数据。 excel文件中的每一行都是一组单独的数据(请求)。我想将这些请求存储在单独的字典中。
request_1 request_2等等(动态,因为它总是在变化)
但是当我的新行和多次迭代时,我被困在如何将数据输入到新词典中。
for items in requestcells:
for row in ws.iter_rows(min_row=items, max_row=items):
for cell in row:
cell_location = (cell.column)
header_text = header_dict[cell_location + "3"]
# This should be request 1 on first iteration and 3rd on second iteration
request_??[header_text] = cell.value
for row in ws.iter_rows(min_row=items + 1, max_row=items + 1):
for cell in row:
cell_location = (cell.column)
header_text = header_dict[cell_location + "3"]
# This should be request 2 on first iteration and 4th on second iteration
request_??[header_text] = cell.value
答案 0 :(得分:2)
不要将变量名称用作数据结构的一部分。变量名是供程序员输入的。如果您使用代码来生成它们,您可能希望代码索引列表或字典。
我会更改您显示的代码,将字典放在列表中,而不是将它们作为每个全局变量。对于您当前与偶数和奇数请求数字交叉的两组不同数据,使用两个单独的列表也是有意义的。
requests = [{} for _ in range(len(requestcells * 2)]
for i, items in enumerate(requestcells):
for row in ws.iter_rows(min_row=items, max_row=items):
for cell in row:
cell_location = (cell.column)
header_text = header_dict[cell_location + "3"]
requests[2*i][header_text] = cell.value
for row in ws.iter_rows(min_row=items + 1, max_row=items + 1):
for cell in row:
cell_location = (cell.column)
header_text = header_dict[cell_location + "3"]
requests[2*i+1][header_text] = cell.value