Python Creating Dictionary from excel data

后端 未结 6 645
梦毁少年i
梦毁少年i 2020-11-30 08:48

I want to create a dictionary from the values, i get from excel cells, My code is below,

wb = xlrd.open_workbook(\'foo.xls\')
sh = wb.sheet_by_index(2)   
f         


        
相关标签:
6条回答
  • 2020-11-30 09:29

    This script allows you to transform an excel data table to a list of dictionaries:

    import xlrd
    
    workbook = xlrd.open_workbook('foo.xls')
    workbook = xlrd.open_workbook('foo.xls', on_demand = True)
    worksheet = workbook.sheet_by_index(0)
    first_row = [] # The row where we stock the name of the column
    for col in range(worksheet.ncols):
        first_row.append( worksheet.cell_value(0,col) )
    # transform the workbook to a list of dictionaries
    data =[]
    for row in range(1, worksheet.nrows):
        elm = {}
        for col in range(worksheet.ncols):
            elm[first_row[col]]=worksheet.cell_value(row,col)
        data.append(elm)
    print data
    
    0 讨论(0)
  • 2020-11-30 09:34

    if you can convert it to csv this is very suitable.

    import dataconverters.commas as commas
    filename = 'test.csv'
    with open(filename) as f:
          records, metadata = commas.parse(f)
          for row in records:
                print 'this is row in dictionary:'+row
    
    0 讨论(0)
  • 2020-11-30 09:43

    I'd go for:

    wb = xlrd.open_workbook('foo.xls')
    sh = wb.sheet_by_index(2)   
    lookup = dict(zip(sh.col_values(2, 0, 138), sh.col_values(0, 0, 138)))
    
    0 讨论(0)
  • 2020-11-30 09:44

    or you can try pandas

    from pandas import *
    xls = ExcelFile('path_to_file.xls')
    df = xls.parse(xls.sheet_names[0])
    print df.to_dict()
    
    0 讨论(0)
  • 2020-11-30 09:44

    You can use Pandas to do this. Import pandas and Read the excel as a pandas dataframe.

    import pandas as pd
    file_path = 'path_for_your_input_excel_sheet'
    df = pd.read_excel(file_path, encoding='utf-16')
    

    You can use pandas.DataFrame.to_dict to convert a pandas dataframe to a dictionary. Find the documentation for the same here

    df.to_dict()
    

    This would give you a dictionary of the excel sheet you read.

    Generic Example :

    df = pd.DataFrame({'col1': [1, 2],'col2': [0.5, 0.75]},index=['a', 'b'])
    

    >>> df

    col1 col2 a 1 0.50 b 2 0.75

    >>> df.to_dict()

    {'col1': {'a': 1, 'b': 2}, 'col2': {'a': 0.5, 'b': 0.75}}

    0 讨论(0)
  • 2020-11-30 09:45
    d = {}
    wb = xlrd.open_workbook('foo.xls')
    sh = wb.sheet_by_index(2)   
    for i in range(138):
        cell_value_class = sh.cell(i,2).value
        cell_value_id = sh.cell(i,0).value
        d[cell_value_class] = cell_value_id
    
    0 讨论(0)
提交回复
热议问题