excel文件作为字典

时间:2017-02-27 14:52:38

标签: python dictionary

我是python的新手,对如何阅读excel文件有疑问。  我有一个excel文件,格式如下:

item     Type    Target   choice1    choice2    
 1       book    pen       pencil      m 
 .        .       .         .          .
 .        .       .         .          .
 n=120

我想编写Python代码,将excel文件读取并打印为字典,如下所示:

trials = {"trial1":["book", "pen", "pencil"]}

我的目标是能够在下面的代码中重新调用它:

trial1_target = trials["trial1"][0] 
trial1_choice1 = trials["trial1"][1] 
trial1_choice2 = trials["trial"][2]    

我尝试在下面的结构中实现代码但是格式错误。你对我有什么建议吗?

import xlrd
file='se_de.xlsx'
workbook = xlrd.open_workbook(file)
worksheet = workbook.sheet_by_name('Sheet1')
num_rows = worksheet.nrows - 1
num_cells = worksheet.ncols - 1
worksheet.cell(0,4)

Lst=list()
for row in range(1, worksheet.nrows):
    Lst.append("Trial"+str(row)+":["+worksheet.cell(row,1)++worksheet.cell(row,2)+worksheet.cell(row,3)"]")

所有评论都会提前感谢。

1 个答案:

答案 0 :(得分:0)

您没有构建有效的数据结构(列表和词典),而是将一堆字符串对象连接在一起。这意味着Python只会将最终输出视为字符串列表。我已将其分解为多个带注释的阶段,以便您可以看到如何构建结构。

# Firstly, the desired structure is a dictionary, not a list, so Lst.append()
# Will never give you the desired output. Create an empty dictionary instead
trials = {}

for row_num in range(1, worksheet.nrows):

    # First build the list portion
    data_list = [worksheet.cell(row_num, 1), worksheet.cell(row_num, 2),
                 worksheet.cell(row_num, 3)]

    # Generate the key
    key = "Trial{}".format(row_num)

    # Add the key, value pair to the dictionary
    trials[key] = data_list