openpyxl读取Excel命名区域 如何将列表转为首行为键的字典列表
实现读取Excel命名区域转字典列表
需求背景
读取Excel命名区域(defined_name)数据时,拿到的是二维列表,需要将其转换为字典列表,用区域第一行的表头作为每个字典的键。
当前读取得到的二维列表结构如下:
[['Country', 'Capital'], ['England', 'London'], ['France', 'Paris'], ['Scotland', 'Edinburgh'], ['Norway', 'Oslo'], ['Finland', 'Helsinki'], ['Spain', 'Madrid'], ['Germany', 'Berlin']]
目标输出格式:
[{'Country': 'England', 'Capital': 'London'}, {'Country': 'France', 'Capital': 'Paris'}, ...]
附原始数据示例:
实现代码
原有读取逻辑只需要简单追加处理步骤即可,注意不要用range做变量名,它是Python内置函数,直接覆盖容易引发后续异常:
# 读取命名区域内容 ws, cell_range = next(wb.defined_names[col[0]].destinations) values = [[cell.value for cell in row] for row in wb[ws][cell_range]] # 提取第一行作为字典键 headers = values[0] # 遍历后续数据行,和表头配对生成字典 dict_list = [dict(zip(headers, row)) for row in values[1:]]
小提示:如果命名区域里存在空行,可以在列表推导式里加过滤条件,比如
[dict(zip(headers, row)) for row in values[1:] if any(cell is not None for cell in row)],就可以跳过全空的无效行。
输出结果
运行后dict_list的内容完全符合预期:
[ {'Country': 'England', 'Capital': 'London'}, {'Country': 'France', 'Capital': 'Paris'}, {'Country': 'Scotland', 'Capital': 'Edinburgh'}, {'Country': 'Norway', 'Capital': 'Oslo'}, {'Country': 'Finland', 'Capital': 'Helsinki'}, {'Country': 'Spain', 'Capital': 'Madrid'}, {'Country': 'Germany', 'Capital': 'Berlin'} ]
内容的提问来源于stack exchange,提问作者EMC
相关产品推荐
相关产品推荐

