简体   繁体   English

在Openpyxl中使用嵌套词典创建列表

[英]Creating a list with nested dictionaries in Openpyxl

I want to loop through all rows in my Excel sheet and store the value of each row (starting at row 2) in individual dictionaries within 1 big list. 我想遍历Excel工作表中的所有行,并将每行(从第2行开始)的值存储在1个大列表内的各个字典中。

I have a simple list of items in an Excel spanning from Column A - Column D: 我在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

I want the very first result to look like: 我希望第一个结果看起来像:

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

Here's how my code looks at the moment: 目前,我的代码如下:

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)

When I run the code, the result prints only the very last active row in the sheet: 当我运行代码时,结果仅打印工作表中的最后一个活动行:

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

I want this format for ALL the rows, not just the final row. 我希望所有行都使用这种格式,而不仅仅是最后一行。 I don't understand why the code is skipping all of the rows in between and just printing the final row. 我不明白为什么代码会跳过中间的所有行,而只打印最后一行。 Could anyone help? 有人可以帮忙吗?

When you assign to allFruits inside your loop you overwrite it on each iteration. 当您在循环内分配allFruits时,您将在每次迭代时将其覆盖。

Instead define the allFruits list outside of your loop and call allFruits.append() inside the loop to add each fruit dictionary. 而是在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})

You could also shorten your code up by doing: 您还可以通过执行以下操作来缩短代码:

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})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM