Python:如何将嵌套列表的字典导出到Excel

我是Python的新手,我很难解决这个问题。

例如,如果我有这样一本字典:

my_dict = {(40987, 'A'): [[1, 2, 3], [0, 1, 0], [0, 1, 1]], (11233, 'R'): [[2, 0, 2], [0, 2, 4]], (10716, 'R'): [[1, 1, 1]], (11049, 'S'): [[6, 0, 5], [2, 5, 7]]} 

我想要的excel文件的结构是:

 Code Letter List0 List1 ... List_n 40987 A [1, 2, 3] [0, 1, 0] 11233 R [2, 0, 2] [0, 2, 4] .... 

有没有办法将这个嵌套列表字典导出到Excel文件?

您可以使用openpyxl模块。

 from openpyxl import Workbook wb=Workbook() dest_filename = 'excelsheet.xlsx' ws1 = wb.active ws1.title = "nested lists" dict={(40987, 'A'): [[1, 2, 3], [0, 1, 0], [0, 1, 1]], (11233, 'R'): [[2, 0, 2], [0, 2, 4]], (10716, 'R'): [[1, 1, 1]], (11049, 'S'): [[6, 0, 5], [2, 5, 7]]} number=1 for item in dict.keys(): ws1.cell(row=number,column=1).value=item[0] ws1.cell(row=number, column=2).value=item[1] r=3 for list in dict[item]: ws1.cell(row=number, column=r).value = str(list) r+=1 number += 1 wb.save(filename = dest_filename) 

对不起,如果这不是最好的方式,我也是一个新的Python。 🙂

这会输出一个可以在Excel中打开的CSV文件。

 import csv my_dict = { (40987, 'A'): [[1, 2, 3], [0, 1, 0], [0, 1, 1]], (11233, 'R'): [[2, 0, 2], [0, 2, 4]], (10716, 'R'): [[1, 1, 1]], (11049, 'S'): [[6, 0, 5], [2, 5, 7]] } # Find the length of the longest list in the dictionary max_list_size = max(len(x) for _, x in my_dict.items()) with open('my_dict.csv', 'w', newline='') as csvfile: dictwriter = csv.writer(csvfile) # Define and write the header row with enough 'listX' columns header = ['Code', 'Letter'] + [f'list{i}' for i in range(max_list_size)] print(header) dictwriter.writerow(header) # Iterate through each entry in the dictionary, writing each row for key, value in my_dict.items(): # Extend the list with blank values (not totally necessary, but keeps the csv file uniform) row = [*key] + value + [""] * (max_list_size - len(value)) print(row) dictwriter.writerow(row) 

注意:这需要现代Python安装。 如果您无法更新,请使用'list{}'.format(i)而不是f'list{i}

可能最简单的方法是将其输出为CSV文件,然后在Excel打开该CSV文件:

 import csv my_dict = {(40987, 'A'): [[1, 2, 3], [0, 1, 0], [0, 1, 1]], (11233, 'R'): [[2, 0, 2], [0, 2, 4]], (10716, 'R'): [[1, 1, 1]], (11049, 'S'): [[6, 0, 5], [2, 5, 7]]} with open('output.csv', 'w', newline='') as csvfile: csvwriter = csv.writer(csvfile, delimiter=';', quoting=csv.QUOTE_NONNUMERIC) for key in my_dict: csvwriter.writerow(list(key) + my_dict[key])