创建 Excel 列值字典的 Pythonic 方法

Pythonic way to create a dict of Excel column values

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

A B C (columns)
1 2 
3 4
5 f

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

cbyc = {'A': [1,3,5]; 'B':[2,4,f]; 'C';[None, None, None]}

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

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)

这项工作,..但我相信有一种更有效的方法可以用 if..else 逻辑创建这个字典

有没有更好的方法?也许openpyxl里面有东西可以给出这样的列表

您可以替换:

if c.column not in cbyc.keys():
    cbyc[c.column] = [c.value]
else:
    cbyc[c.column].append(c.value)

与:

cby.setdefault(c.column, []).append(c.value)
setdefault(key[, default])

If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

docs

from collections import defaultdict

cbyc = defaultdict(list)

for cell in all_cells:
    if cell.value is None:
        continue
    cbyc[cell.column].append(cell.value)

documentation on defaultdict

每当我看到填充 dictlist 的难看循环时,我都会尝试将其替换为字典理解或列表理解。在这种情况下,我会同时使用两者。

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

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)

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

cybc = { col[0]: col[1:] for col in zip(*sheet.values) }