首页 > 解决方案 > 我想在python中以字典的形式显示一列Excel

问题描述

我的 excel 文件中有一列,我必须将该列的所有行转换为字典格式。我的文件像这样,有 802 行: 在此处输入图像描述

和我的预期输出:

ldict = {
"item1": set(["5"]),
"item2": set(["2"]),
"item3": set(["0"]),
"item4": set(["1"]),
"item5": set(["6"]),
"item6": set(["6"]),
"item7": set(["1"]),

} 请帮我。

标签: pythonexceldictionary

解决方案


安装openpyxl包(如果你还没有的话),然后执行:

import openpyxl

# Access active worksheet of excel file
book = openpyxl.load_workbook('workbook.xlsx')
sheet = book.active

# Access first column
column = sheet['A']

# Use dictionary comprehension on the cells in the column
d = {
    'item{}'.format(num): cell.value
    for (num, cell) in enumerate(column, 1)
}

推荐阅读