You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的openpyxl按行而非按列生成指定格式字典

解决方法

你需要先提取表头作为字典的键,再逐行读取后续数据,将每行数据与表头配对生成字典,最终收集为列表。修改后的代码如下:

from openpyxl import load_workbook

wb = load_workbook('itemtablex.xlsx')
ws = wb['Sheet1']

# 获取第一行作为表头(字典的键)
headers = next(ws.values)
# 遍历后续每一行,生成字典并收集到列表中
all_item_list = []
for row in ws.values:
    # 将表头与当前行数据配对成字典
    item_dict = dict(zip(headers, row))
    all_item_list.append(item_dict)

print(all_item_list)

代码说明

  • next(ws.values):获取工作表的第一行数据(表头),作为后续字典的键。
  • 遍历ws.values时,因为next已经取走了第一行,后续循环会自动从第二行开始读取数据。
  • dict(zip(headers, row)):将表头与当前行的每一列数据一一对应,生成符合要求的字典,再添加到结果列表中。

执行后会生成你需要的结构:

[{"title": "Ball", "Price": 100, "Link": "Link", "Description": "text"}, {"title": "Tshort", "Price": 200, "Link": "Link2", "Description": "text2"}]

内容的提问来源于stack exchange,提问作者denis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 12:21:02