使用python从不同行和列中的excel单元格创建字典

时间:2016-02-11 22:44:54

标签: python excel dictionary

我想创建一个字典,将项目代码与其对应的总成本值相匹配。值位于不同的行和不同的列中。但是,可以引用其他单元格来获取值。 excel表看起来像这样:

      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"

创建此词典的最佳方法是什么?

2 个答案:

答案 0 :(得分:0)

这看起来很有希望。 xlrd and xlwt

我想我会用这个用正则表达式遍历单元格并附加到dict。我是python的新手,所以这可能不是一个很好的解决方案。

答案 1 :(得分:0)

这在技术上有用...如果您知道如何使代码更漂亮,请告诉我。

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