1

我是 python 新手,但我一直在尝试创建一个从 Excel 文件中读取(openpyxl)的字典列表。使用 iter_rows() 读取文件中的所有行,然后将每一行添加为字典。然后脚本将该字典附加到一个列表中,但是在查看字典列表时,它只显示最后一行(或字典)被附加了几次。我不确定为什么它只附加最后一行?

输入 Excel 文件

import openpyxl
 
# Give the location of the file
path = 'C:\\Users\\.....\\pythonExcelDemo.xlsx'
 
# workbook object is created
wb_obj = openpyxl.load_workbook(path)

thisList = []
inner_dict = {}

sheet_obj = wb_obj.active

for row in sheet_obj.iter_rows(2, 6, 1, 3):
    for cell in row:
        if cell.column == 1:
            inner_dict.update({'Students Name': cell.value})
        if cell.column == 2:
            inner_dict.update({'Department': cell.value})
        if cell.column == 3:
            inner_dict.update({'Fund': cell.value})
    thisList.append(inner_dict)    
print(thisList)


Output-----

[{'Students Name': 'Keli', 'Department': 'Branch', 'Fund': 160}, {'Students Name': 'Keli', 'Department': 'Branch', 'Fund': 160}, {'Students Name': 'Keli', 'Department': 'Branch', 'Fund': 160}, {'Students Name': 'Keli', 'Department': 'Branch', 'Fund': 160}, {'Students Name': 'Keli', 'Department': 'Branch', 'Fund': 160}]
4

1 回答 1

1

What you're missing here is key point about Python. You're not creating a set of dictionaries. You're creating exactly ONE dictionary, modifying it during each loop, and creating a list with many references to that one dictionary. When you change one, you change them all. You need to create a new dict every loop. Do this:

for row in sheet_obj.iter_rows(2, 6, 1, 3):
    inner_dict = {}
    for cell in row:
        if cell.column == 1:
            inner_dict['Students Name'] = cell.value
        elif cell.column == 2:
            inner_dict['Department'] = cell.value
        elif cell.column == 3:
            inner_dict['Fund'] = cell.value
    thisList.append(inner_dict)    
print(thisList)
于 2021-07-04T03:26:25.323 回答