【问题标题】:Printing keys and values of a dictionary created from excel using xlrd使用 xlrd 打印从 excel 创建的字典的键和值
【发布时间】:2017-04-25 16:21:08
【问题描述】:
import xlrd
import os

wb = xlrd.open_workbook (os.path.expanduser("~/Documents/Python/HRCQ determination TABLE.xls"))
sheet = wb.sheet_by_name('Sheet1')


sheetdict = {}

#build ductionary3
for rownum in range(sheet.nrows):
    sheetdict[sheet.cell(rownum,0)] = [sheet.cell(rownum,1)]

#test print dictionary in format: Co-60 - 16 Ci
for keys,values in sheetdict.items():
    print(keys,values)

这段代码的输出最终是

text:'AC225' [number:0.16]
text:'AC227' [number:0.0024]
text:'AC228' [number:14.0]
text:'AG105' [number:54.0]
text:'AG108M' [number:19.0]
text:'AG110M' [number:11.0]

等等。

我不知道 text: 和 [number: ____] 的来源。我认为它们实际上是从 excel 存储在字典中的数据的一部分,但我不知道如何删除它或 excel 正在做什么导致它。

我对 Python 非常陌生(一般是编码),因此非常感谢所有帮助。

【问题讨论】:

    标签: python excel dictionary printing xlrd


    【解决方案1】:

    xlrd 中调用Sheet 对象的.cell 方法实际上返回一个Cell 对象。这个Cell 对象并不完全是您正在查找的值。如果您需要该值本身,则需要使用Cell 对象的.value 属性来访问它。总之,您需要使用sheetdict[sheet.cell(rownum,0).value] = [sheet.cell(rownum,1).value] 专门访问Cell 对象的.value 属性,而不是sheetdict[sheet.cell(rownum,0)] = [sheet.cell(rownum,1)]

    因此,您的脚本将是:

    import xlrd
    import os
    
    wb = xlrd.open_workbook (os.path.expanduser("~/Documents/Python/HRCQ determination TABLE.xls"))
    sheet = wb.sheet_by_name('Sheet1')
    
    
    sheetdict = {}
    
    #build ductionary3
    for rownum in range(sheet.nrows):
        sheetdict[sheet.cell(rownum,0).value] = [sheet.cell(rownum,1).value]
    
    #test print dictionary in format: Co-60 - 16 Ci
    for keys,values in sheetdict.items():
        print(keys,values)
    

    另外,为了避免处理Cell 对象,您可以使用Sheet 对象的.col_values 方法直接访问您正在工作的两列(0 和1)中的每一列的值和。这将生成两个值列表,您可以将它们zip 一起转换为dictionary。以下是上述脚本的调整版本:

    import xlrd
    import os
    
    wb = xlrd.open_workbook (os.path.expanduser("~/Documents/Python/HRCQ determination TABLE.xls"))
    sheet = wb.sheet_by_name('Sheet1')
    
    # get column values, zip them together and convert the output into a dictionary
    sheetdict = dict(zip(*[sheet.col_values(i) for i in range(2)]))
    
    for keys,values in sheetdict.items():
        print(keys,values)
    

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 2016-12-01
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      相关资源
      最近更新 更多