在Python中从Excel单元格创建字典

时间:2019-06-26 12:49:37

标签: python spyder xlrd xlwt

我有一个Excel文件,其中每个单元格都有一个标题,其值(整数,字符串或无)由:符号分隔。我想制作一个字典,其中键可以是标题。

excel文件中的列如下所示:

Procedure: PicProc  #cell 1
Mod: avB            #cell 2
ImageFile: av.jpg   #so on 
Odor: 1
OlfClass: 1
Jitter: 9500
ScaleDur: 4500
OdorList.Cycle: 1
OdorList.Sample: 10
Running: OdorList
FixationBlack.OnsetDelay: 2893
FixationBlack.OnsetTime: 217369
FixationBlack.RESP: 
FixationBlack1.OnsetDelay: 27
FixationBlack1.OnsetTime: 226896
FixationBlack1.RESP: 
FixationYellow.RESP: 
PicPresent.OnsetDelay: 34
PicPresent.OnsetTime: 227547
PicPresent.RESP: 
RatingOnset: 230558

我想要这样的东西:

{'Procedure': 'PicProc','Mod': 'avB', 'ImageFile': 'av.jpg','Odor': '1'...  }

我该怎么做?

3 个答案:

答案 0 :(得分:0)

enter image description here

您可以使用此代码访问Excel并获取值 如您在图像中看到的,您可以获得标题的第一行 因此您将拥有:区域;底部区域1等 并获取第二,第三等行的值。 结果,您将拥有 Area =“ Campalto”; Sotto-area1 =“”等

# Reading an excel file using Python 
import xlrd 

# Give the location of the file 
loc = ("path of file") 

# To open Workbook 
wb = xlrd.open_workbook(loc) 
sheet = wb.sheet_by_index(0) 

# For row 0 and column 0 
sheet.cell_value(0, 0) //this will return the value of the first cell ... that has position 0,0

答案 1 :(得分:0)

my_dict = {}
loc = ("path of file")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
for i in range(1, sheet.nrows):

    row = sheet.row_values(i)
    my_dict[row[0]] = row[1]

print(my_dict)

希望有帮助。

答案 2 :(得分:0)

假设您的数据放在工作簿的第一页中,column A内,您可以像这样提取数据:

import xlrd


wb = xlrd.open_workbook("path/to/file")
sheet = wb.sheet_by_index(0) # First sheet of workbook
arr = sheet.col_values(0) # Column A

print({k:v.strip() for k, v in dict(s.split(':', 1) for s in arr).items()})

输出

{'Procedure': 'PicProc', 'Mod': 'avB', 'ImageFile': 'av.jpg', 'Odor': '1', 'OlfClass': '1', 'Jitter': '9500', 'ScaleDur': '4500', 'OdorList.Cycle': '1', 'OdorList.Sample': '10', 'Running': 'OdorList', 'FixationBlack.OnsetDelay': '2893', 'FixationBlack.OnsetTime': '217369', 'FixationBlack.RESP': '', 'FixationBlack1.OnsetDelay': '27', 'FixationBlack1.OnsetTime': '226896', 'FixationBlack1.RESP': '', 'FixationYellow.RESP': '', 'PicPresent.OnsetDelay': '34', 'PicPresent.OnsetTime': '227547', 'PicPresent.RESP': '', 'RatingOnset': '230558'}