如何使用 openpyxl 从 excel sheet 中的行创建列表,然后将它们插入字典中?
How can I use openpyxl to create a list out of the rows in an excel sheet and then insert them into a dictionary?
我在 excel 中有一个 2X4 table 的数字,如下所示:
0.454 0.253
0.345 0.768
0.853 0.098
0.948 0.593
我想将其中的每一行转换成一个单独的列表,并将该列表分配为字典中的一个值,其中的键是行号。所以字典将是:
{1: (0.454, 0.253), 2: (0.345, 0.768), 3: (0.853, 0.098), 4: (0.948, 0.593)}
我不知道该怎么做。
这对我有用。 请记住,您需要将“ws”替换为您命名的工作表并加载正确的工作簿。我在下面的代码中解释了所有内容。但我也会在这里解释。
这会创建一个字典,然后使用 for 循环从电子表格中获取值。这些值将被添加到一个列表中,然后该列表被放入一个新键下的初始字典中,该键将与使用的行匹配!
#Loading workbook and initializing the sheet
wb = load_workbook("tax log1.xlsx")
ws = wb.active
#Creates empty dictionary - Loop below adds values
cell_row_dict = {}
#Loops through first 4 rows
for y in range(1, 5):
#Getting Values from spreadsheet
value_to_add1 = ws.cell(row=y, column=1).value
value_to_add2 = ws.cell(row=y, column=2).value
#This creates a list of the values in the column and also clears it out to ready for nxt loop
list = []
list.append(value_to_add1)
list.append(value_to_add2)
#Adds the newly created list to a new key.. which will be Y as thats how many rows are used.
cell_row_dict.update({y:list})
#Print final dictionary - Success!!
print(cell_row_dict)
如果出于某种原因最终有更多的列,我建议使用更多循环来附加列表并获取值。
我在 excel 中有一个 2X4 table 的数字,如下所示:
0.454 0.253
0.345 0.768
0.853 0.098
0.948 0.593
我想将其中的每一行转换成一个单独的列表,并将该列表分配为字典中的一个值,其中的键是行号。所以字典将是:
{1: (0.454, 0.253), 2: (0.345, 0.768), 3: (0.853, 0.098), 4: (0.948, 0.593)}
我不知道该怎么做。
这对我有用。 请记住,您需要将“ws”替换为您命名的工作表并加载正确的工作簿。我在下面的代码中解释了所有内容。但我也会在这里解释。
这会创建一个字典,然后使用 for 循环从电子表格中获取值。这些值将被添加到一个列表中,然后该列表被放入一个新键下的初始字典中,该键将与使用的行匹配!
#Loading workbook and initializing the sheet
wb = load_workbook("tax log1.xlsx")
ws = wb.active
#Creates empty dictionary - Loop below adds values
cell_row_dict = {}
#Loops through first 4 rows
for y in range(1, 5):
#Getting Values from spreadsheet
value_to_add1 = ws.cell(row=y, column=1).value
value_to_add2 = ws.cell(row=y, column=2).value
#This creates a list of the values in the column and also clears it out to ready for nxt loop
list = []
list.append(value_to_add1)
list.append(value_to_add2)
#Adds the newly created list to a new key.. which will be Y as thats how many rows are used.
cell_row_dict.update({y:list})
#Print final dictionary - Success!!
print(cell_row_dict)
如果出于某种原因最终有更多的列,我建议使用更多循环来附加列表并获取值。