在Openpyxl中创建包含嵌套字典的列表

时间:2017-08-03 16:25:35

标签: python excel dictionary python-3.5 openpyxl

我想遍历Excel表格中的所有行,并将每行的值(从第2行开始)存储在1个大列表中的单个词典中。

我在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 行,而不仅仅是最后一行。我不明白为什么代码跳过其间的所有行并只打印最后一行。有人可以帮忙吗?

1 个答案:

答案 0 :(得分: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})
相关问题