使用python从不同行和列中的excel单元格创建字典
我想创建一个字典,使项目代码与其对应的总成本值相匹配。这些值位于不同的行和列中。但是,可以引用其他单元格来获取值。excel工作表如下所示:使用python从不同行和列中的excel单元格创建字典,python,excel,dictionary,Python,Excel,Dictionary,我想创建一个字典,使项目代码与其对应的总成本值相匹配。这些值位于不同的行和列中。但是,可以引用其他单元格来获取值。excel工作表如下所示: A B C D E 1 Project A1-234 Something Something 2 does not matter 3 Total 1234 4 5 Projec
A B C D E
1 Project A1-234 Something Something
2 does not matter
3 Total 1234
4
5 Project A2-912 Something Something
6 also does not matter
7 another will not matter
8 Total 789
项目代码是键,总值是字典的值。基于此,我将有2个键值对:
dict = {
"A1-234": 1234,
"A2-912": 789
}
有很多项目,但它们都具有以下一致性:
"Project": Always in column A
ProjectCode: Always in column B in the same row as "Project"
"Total": Always in column A
TotalAmount: Always in Column E in the same row as "Total"
创建此词典的最佳方法是什么?这看起来很有希望
我想我会用它来循环使用regex的单元格并附加到dict中。我是python新手,所以这可能不是一个很好的解决方案 这在技术上是可行的。。。如果你知道如何使代码更漂亮,请让我知道
from xlrd import *
# workbook containing the entire projects
wb = open_workbook("C:/Users/my.name/Documents/Projects.xlsx")
worksheet1 = wb.sheet_by_name("Sheet1")
project_dict = {}
project_key_column = 1
total_value_column = 4
total_found = True
project_key = ""
# store the project key and Total value into a dictionary
for row_num in xrange(worksheet.nrows):
# find a row with Ai=Project and set project_key to the key value next to it
if worksheet.cell(row_num, 0).value == "Project":
if not total_found: # the total should be found before a second occurrence of Project
print "WARNING: Project %s did not find a value row" % project_key
project_key = worksheet.cell(row_num, project_key_column).value
total_found = False # find the value for the new Project key
# find a row with Ai=Total and set the value in the G column to total
if worksheet.cell(row_num, 0).value == "Total":
total = worksheet.cell(row_num, total_value_column).value
if total == "":
print "WARNING: Project %s contains an empty Value" % project_key
project_dict[project_key] = total # add the key value pair of the project_key and total
total_found = True
我无法想象一个简单的解决方案,只有一大堆if语句。(例如,如果行[0]=“项目”:键=行[1];get_total=True)