2017-08-03 116 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

這完美的作品,非常感謝。 –