问题
我想把一个excel数据转化成字典。其中第一列作为key值,
其他列合并成列表作为值。
表格:
col0 | col1 | col2 | col3 |
---|---|---|---|
a | 1 | 2 | 3 |
b | 4 | 5 | 6 |
c | 7 | 8 | 9 |
a | 10 | 11 | 12 |
b | 13 | 14 | 15 |
c | 16 | 17 | 18 |
预期效果是
{
‘a’:[[1, 2, 3],[10, 11, 12]…]
‘b’:[[4, 5, 6],[13, 14, 15]…]
‘c’:[[7, 8, 9],[16, 17, 18]…]
}
刚开始用了这样的代码尝试:
def read_excel(bookname, sheetname):
# 打开Excel文件
wb = xlrd.open_workbook(bookname)
sheet = wb.sheet_by_name(sheetname)
dic = {}
for i in range(sheet.nrows - 1):
lis = []
for j in range(sheet.ncols):
lis.append(sheet.cell(i + 1, j).value)
dic[sheet.cell(i + 1, 0).value] = lis #第一列作为key
print(dic)
return dic
但是由于表格中有大量重复的key,所以结果是后面的value值会覆盖前面的,得到的结果是
{
‘a’:[10, 11, 12]
‘b’:[13, 14, 15]
‘c’:[16, 17, 18]
}
解决
def read_excel(bookname, sheetname):
# 打开Excel文件
wb = xlrd.open_workbook(bookname)
sheet = wb.sheet_by_name(sheetname)
dic = {}
for i in range(sheet.nrows - 1):
lis = []
for j in range(sheet.ncols):
lis.append(sheet.cell(i + 1, j).value)
# dic[sheet.cell(i + 1, 2).value] = lis #第一列作为key
if sheet.cell(i+1, 2).value not in dic:
dic[sheet.cell(i + 1, 2).value] = [lis]
else:
dic[sheet.cell(i+1, 2).value].append(lis)
# print(dic)
return dic
扩展
将字典转回excel
def write_back(dic):
book = xlwt.Workbook(encoding='utf-8', style_compression=0)
sheet = book.add_sheet('test', cell_overwrite_ok=True)
# m = 0
#
# for i in dic.keys():
# m += 1
# n = 0
# for j in dic[i]:
# sheet.write(m, n, str(j))
# n += 1
# sheet.write(0, 0, '用户类型')
# sheet.write(0, 1, '序号')
# sheet.write(0, 2, '用户名')
# sheet.write(0, 3, '用户类型')
# sheet.write(0, 4, '微博内容')
linenum = 0
for key, value in dic.items():
for lis in value:
linenum += 1
sheet.write(linenum, 0, key)
colnum = 1
for v in lis:
sheet.write(linenum, colnum, v)
colnum += 1
# linenum += 1
book.save('selecn.xls')