python的excel转重复key字典问题

本文介绍了一种将Excel数据转换为Python字典的方法,其中第一列作为key,其余列作为值的列表,特别关注处理重复key的问题。同时,提供了将字典数据回写到Excel的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题

我想把一个excel数据转化成字典。其中第一列作为key值,
其他列合并成列表作为值。

表格:

col0col1col2col3
a123
b456
c789
a101112
b131415
c161718

预期效果是

{
‘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')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值