2017-08-03 47 views
0

我想遍历Excel工作表中的所有行,并将每行(从第2行开始)的值存储在1大列表中的各个字典中。在Openpyxl中使用嵌套字典创建列表

我有一个Excel项目从A柱横跨的简单列表 - 列d:

Fruit: Quantity: Color: Cost 
Apple 5   Red  0.6 
Banana 6   Yellow 0.4 
Orange 4   Orange 0.3 
Kiwi 2   Green 0.1 

我想看看的第一个结果是这样的:

[{'Fruit': 'Apple', 'Quantity': 5, 'Color': 'Red', 'Cost': 0.6}] 

下面是我的代码看看此刻:

import openpyxl 
wb = openpyxl.load_workbook('fruit.xlsx') 
sheet = wb.get_sheet_by_name('Sheet1') 

for row in range(2, sheet.max_row + 1): 
    fruit = sheet['A' + str(row)].value 
    quantity = sheet['B' + str(row)].value 
    color = sheet['C' + str(row)].value 
    cost = sheet['D' + str(row)].value 

    allFruits = [{'Fruit': fruit, 
       'Quantity': quantity, 
       'Color': color, 
       'Cost': cost}] 

print(allFruits) 

当我运行代码时,结果只打印最后一个活动行在表:

[{'Fruit': 'Kiwi', 'Quantity': 2, 'Color': 'Green', 'Cost': 0.1}] 

我想这种格式ALL行,而不仅仅是最后一行。我不明白为什么代码跳过其中的所有行,只是打印最后一行。谁能帮忙?

回答

2

当您在循环中指定allFruits时,将在每次迭代时覆盖它。

取而代之,在循环外部定义allFruits列表并在循环内调用allFruits.append()以添加每个水果字典。

allFruits = [] 

for row in range(2, sheet.max_row + 1): 
    fruit = sheet['A' + str(row)].value 
    quantity = sheet['B' + str(row)].value 
    color = sheet['C' + str(row)].value 
    cost = sheet['D' + str(row)].value 

    allFruits.append({'Fruit': fruit, 
       'Quantity': quantity, 
       'Color': color, 
       'Cost': cost}) 

你也可以缩短你的代码了做:

allFruits = [] 
key_col = [('Fruit', 'A'), ('Quantity', 'B'), ('Color', 'C'), ('Cost', 'D')] 

for row in range(2, sheet.max_row + 1): 
    allFruits.append({key:sheet[col+str(row)].value for (key, col) in key_col}) 
+0

这完美的作品,非常感谢。 –