Python 使用openpyxl创建一个字典,其中key是excel工作表中的标题名称

Python 使用openpyxl创建一个字典,其中key是excel工作表中的标题名称,python,excel,dictionary,openpyxl,Python,Excel,Dictionary,Openpyxl,上面是我的示例代码 我有一个excel表格,它的标题是var1、var2、var3。我想创建一个字典{Var1:1,4,7,10},其中Var1是标题名,值是相应的列值。我使用的是openpyxl模块。在这里,变量名和值将由用户给出,它们将是动态的 Var1 Var2 Var3 1 2 3 4 5 6 7 8 9 101112 这是: from openpyxl import * Variable_Model_Path=defaultdict(list) Sheet_Name=wb.get_s

上面是我的示例代码

我有一个excel表格,它的标题是var1、var2、var3。我想创建一个字典{Var1:1,4,7,10},其中Var1是标题名,值是相应的列值。我使用的是openpyxl模块。在这里,变量名和值将由用户给出,它们将是动态的

Var1 Var2 Var3

  • 1 2 3
  • 4 5 6
  • 7 8 9
  • 101112
    • 这是:

      from openpyxl import *
      Variable_Model_Path=defaultdict(list)
      Sheet_Name=wb.get_sheet_by_name(Sheet)
      for row in Sheet_Name.iter_rows():
          Row=[cell.value for cell in row]
          for cell_ind,cell in enumerate(Row):
              print cell
      
      给我:

      from openpyxl    import *
      from collections import defaultdict
      path  = "/Users/romain/Desktop/Classeur2.xlsx"
      Sheet = "Feuil1"
      wb    = load_workbook(path)
      
      Variable_Model_Path = defaultdict(list)
      Sheet_Name          = wb.get_sheet_by_name(Sheet)
      keys                = False
      
      for row in Sheet_Name.iter_rows():
          if not keys:
              keys = [cell.value for cell in row]
              continue
          Row=[cell.value for cell in row]
          for cell_ind,cell in enumerate(Row):
              Variable_Model_Path[keys[cell_ind]].append( cell)
      
      这:

      from openpyxl import *
      Variable_Model_Path=defaultdict(list)
      Sheet_Name=wb.get_sheet_by_name(Sheet)
      for row in Sheet_Name.iter_rows():
          Row=[cell.value for cell in row]
          for cell_ind,cell in enumerate(Row):
              print cell
      
      给我:

      from openpyxl    import *
      from collections import defaultdict
      path  = "/Users/romain/Desktop/Classeur2.xlsx"
      Sheet = "Feuil1"
      wb    = load_workbook(path)
      
      Variable_Model_Path = defaultdict(list)
      Sheet_Name          = wb.get_sheet_by_name(Sheet)
      keys                = False
      
      for row in Sheet_Name.iter_rows():
          if not keys:
              keys = [cell.value for cell in row]
              continue
          Row=[cell.value for cell in row]
          for cell_ind,cell in enumerate(Row):
              Variable_Model_Path[keys[cell_ind]].append( cell)
      

      我无法理解您的问题是什么?我想将标题表示为键,将相应的列值表示为值以形成字典。我无法理解您的问题是什么?我想将标题表示为键,将相应的列值表示为值以形成字典。谢谢您的回答,这正是我想要的,但我怎样才能把它们整理好呢?我的意思是,当我为我的excel工作表执行此代码时,列没有排序,我的意思是第一列出现在最后,字典中的中间列首先出现。如果没有键,则键的作用是什么:键=[cell.value for cell in row]在上述代码中继续吗?谢谢你的回答,这正是我想要的,但是我怎样才能把它们整理好呢?我的意思是,当我为我的excel工作表执行此代码时,列没有排序,我的意思是第一列出现在最后,字典中的中间列首先出现。如果没有键,则键的作用是什么:键=[cell.value for cell in row]在上述代码中是否继续?