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

前端 未结 5 719
萌比男神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条回答
  •  借酒劲吻你
    2020-12-24 03:02

    from xlrd import open_workbook
    
    dict_list = []
    book = open_workbook('forum.xlsx')
    sheet = book.sheet_by_index(3)
    
    # read first row for keys  
    keys = sheet.row_values(0)
    
    # read the rest rows for values
    values = [sheet.row_values(i) for i in range(1, sheet.nrows)]
    
    for value in values:
        dict_list.append(dict(zip(keys, value)))
    
    print dict_list
    

提交回复
热议问题