XLRD/Python: Reading Excel file into dict with for-loops

前端 未结 5 718
萌比男神i
萌比男神i 2020-12-24 02:19

I\'m looking to read in an Excel workbook with 15 fields and about 2000 rows, and convert each row to a dictionary in Python. I then want to append each dictionary to a list

5条回答
  •  梦毁少年i
    2020-12-24 02:46

    Try to first set up your keys by parsing just the first line, all columns, another function to parse the data, then call them in order.

    all_fields_list = []
    header_dict = {}
    def parse_data_headers(sheet):
       global header_dict
       for c in range(sheet.ncols):
           key = sheet.cell(1, c) #here 1 is the row number where your header is
           header_dict[c] = key   #store it somewhere, here I have chosen to store in a dict
    def parse_data(sheet):
       for r in range(2, sheet.nrows):
           row_dict = {}
           for c in range(sheet.ncols):
               value = sheet.cell(r,c)
               row_dict[c] = value
           all_fields_list.append(row_dict)
    

提交回复
热议问题