栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

XLRD / Python:使用for循环将Excel文件读入dict

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

XLRD / Python:使用for循环将Excel文件读入dict

这个想法是,首先,将标题读入列表。然后,迭代工作表行(从标题后的下一个开始),基于标题键和适当的单元格值创建新字典,并将其附加到词典列表中:

from xlrd import open_workbookbook = open_workbook('forum.xlsx')sheet = book.sheet_by_index(3)# read header values into the list    keys = [sheet.cell(0, col_index).value for col_index in xrange(sheet.ncols)]dict_list = []for row_index in xrange(1, sheet.nrows):    d = {keys[col_index]: sheet.cell(row_index, col_index).value          for col_index in xrange(sheet.ncols)}    dict_list.append(d)print dict_list

对于包含以下内容的工作表:

A   B   C   D1   2   3   45   6   7   8

它打印:

[{'A': 1.0, 'C': 3.0, 'B': 2.0, 'D': 4.0},  {'A': 5.0, 'C': 7.0, 'B': 6.0, 'D': 8.0}]

UPD(扩展字典理解):

d = {}for col_index in xrange(sheet.ncols):    d[keys[col_index]] = sheet.cell(row_index, col_index).value


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/517139.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号