Pythonic方法创建Excel列值的字典

nit*_*tin 0 python excel dictionary openpyxl

我有一个Excel工作表,我想创建一个dict,其单元格值作为列表,单元格列是关键.假设电子表格的数据看起来像,

A B C (columns)
1 2 
3 4
5 f
Run Code Online (Sandbox Code Playgroud)

我想要一个看起来像的字典,

cbyc = {'A': [1,3,5]; 'B':[2,4,f]; 'C';[None, None, None]}
Run Code Online (Sandbox Code Playgroud)

我使用以下代码执行此操作

import openpyxl as oxl
wb = oxl.load_workbook('myxlworkbook.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
allcells = sheet.get_cell_collection()

cbyc = {}
for c in allcells:
    if c.value is not None:
        if c.column not in cbyc.keys():
            cbyc[c.column] = [c.value]
        else:
            cbyc[c.column].append(c.value)
Run Code Online (Sandbox Code Playgroud)

这项工作,...但我相信有一种更有效的方法来创建这个dict与if .. else逻辑

有没有更好的办法?也许openpyxl中有一些东西可以提供这样的列表

Rob*_*obᵩ 6

每当我看到一个难看的循环填充a dict或a时list,我会尝试用dict理解或列表理解来替换它.在这种情况下,我会同时使用两者.

这个程序可能会做你想要的:

import openpyxl as oxl
wb = oxl.load_workbook('myxlworkbook.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')

cybc = {
    col[0].value: [cell.value for cell in col[1:]]
    for col in sheet.columns
}

print(cybc)
Run Code Online (Sandbox Code Playgroud)

但是,.value如果我们调用sheet.values以开头,我们可以避免所有代码:

cybc = { col[0]: col[1:] for col in zip(*sheet.values) }
Run Code Online (Sandbox Code Playgroud)