【问题标题】:Python Creating Dictionary from excel dataPython从excel数据创建字典
【发布时间】:2013-01-07 12:31:38
【问题描述】:

我想从值创建一个字典,我从 excel 单元格中获取, 我的代码如下,

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

我想创建一个字典,如下所示,其中包含来自 excel 单元格的值;

{'class1': 1, 'class2': 3, 'class3': 4, 'classN':N}

知道如何创建这本字典吗?

【问题讨论】:

    标签: python xlrd


    【解决方案1】:

    或者你可以试试pandas

    from pandas import *
    xls = ExcelFile('path_to_file.xls')
    df = xls.parse(xls.sheet_names[0])
    print df.to_dict()
    

    【讨论】:

    • +1 给你这个概念!
    【解决方案2】:

    此脚本允许您将 excel 数据表转换为字典列表:

    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
    

    【讨论】:

      【解决方案3】:
      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
      

      【讨论】:

      • d 是字典对象还是任何数组?
      • @PythonLikeYOU - 根据d = {},它是一本字典。
      • +1 给你这个概念。
      • @eumiro 你能看看这个帖子file download
      【解决方案4】:

      您可以使用 Pandas 来执行此操作。导入 pandas 并将 excel 作为 pandas 数据框读取。

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

      您可以使用 pandas.DataFrame.to_dict 将 pandas 数据框转换为字典。 Find the documentation for the same here

      df.to_dict()
      

      这将为您提供您阅读的 excel 表的字典。

      通用示例:

      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}}

      【讨论】:

        【解决方案5】:

        如果您想使用 pandas 将 Excel 数据转换为 python 中的字典列表, 最好的方法:

        excel_file_path = 'Path to your Excel file'
        excel_records = pd.read_excel(excel_file_path)
        excel_records_df = excel_records.loc[:, ~excel_records.columns.str.contains('^Unnamed')]
        records_list_of_dict=excel_records_df.to_dict(orient='record')
        Print(records_list_of_dict)
        

        【讨论】:

          【解决方案6】:

          还有一个 PyPI 包:https://pypi.org/project/sheet2dict/ 它正在解析 excel 和 csv 文件并将其作为字典数组返回。 每一行都表示为数组中的一个字典。

          像这样:

          Python 3.9.0 (default, Dec  6 2020, 18:02:34)
          [Clang 12.0.0 (clang-1200.0.32.27)] on darwin
          Type "help", "copyright", "credits" or "license" for more information.
          
          # Import the library
          >>> from sheet2dict import Worksheet
          
          # Create an object
          >>> ws = Worksheet()
          
          # return converted rows as dictionaries in the array 
          >>> ws.xlsx_to_dict(path='Book1.xlsx')
          [
              {'#': '1', 'question': 'Notifications Enabled', 'answer': 'True'}, 
              {'#': '2', 'question': 'Updated', 'answer': 'False'}
          ]
          

          【讨论】:

            【解决方案7】:

            我会去:

            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)))
            

            【讨论】:

              【解决方案8】:

              如果你能把它转换成 csv 那就很合适了。

              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
              

              【讨论】:

                【解决方案9】:

                如果你使用,openpyxl 下面的代码可能会有所帮助:

                import openpyxl
                workbook = openpyxl.load_workbook("ExcelDemo.xlsx")
                sheet = workbook.active
                first_row = [] # The row where we stock the name of the column
                for col in range(1, sheet.max_column+1):
                    first_row.append(sheet.cell(row=1, column=col).value)
                data =[]
                for row in range(2, sheet.max_row+1):
                    elm = {}
                    for col in range(1, sheet.max_column+1):
                        elm[first_row[col-1]]=sheet.cell(row=row,column=col).value
                    data.append(elm)
                print (data)
                

                感谢:Python Creating Dictionary from excel data

                【讨论】:

                  猜你喜欢
                  • 2020-06-11
                  • 2019-07-24
                  • 2020-12-23
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2016-05-09
                  相关资源
                  最近更新 更多