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

前端 未结 5 723
萌比男神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 02:44

    The idea is to, first, read the header into the list. Then, iterate over the sheet rows (starting from the next after the header), create new dictionary based on header keys and appropriate cell values and append it to the list of dictionaries:

    from xlrd import open_workbook
    
    book = open_workbook('forum.xlsx')
    sheet = book.sheet_by_index(3)
    
    # read header values into the list    
    keys = [sheet.cell(0, col_index).value for col_index in xrange(sheet.ncols)]
    
    dict_list = []
    for row_index in xrange(1, sheet.nrows):
        d = {keys[col_index]: sheet.cell(row_index, col_index).value 
             for col_index in xrange(sheet.ncols)}
        dict_list.append(d)
    
    print dict_list
    

    For a sheet containing:

    A   B   C   D
    1   2   3   4
    5   6   7   8
    

    it prints:

    [{'A': 1.0, 'C': 3.0, 'B': 2.0, 'D': 4.0}, 
     {'A': 5.0, 'C': 7.0, 'B': 6.0, 'D': 8.0}]
    

    UPD (expanding the dictionary comprehension):

    d = {}
    for col_index in xrange(sheet.ncols):
        d[keys[col_index]] = sheet.cell(row_index, col_index).value 
    

提交回复
热议问题