2017-06-02 55 views
1

我是Python的新手,我很難解決此問題。Python:如何將嵌套列表字典導出到Excel

舉例來說,如果我有這樣一個字典:

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文件?

+0

請註明Excel中所需的結構,什麼是頭,等.... –

回答

0

您可以使用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有點新。 :)

+0

謝謝您!優秀的答案! – Zeno

0

這會輸出一個可以在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}

+0

謝謝你的回答! – Zeno

0

可能是最簡單的方法就是輸出它作爲CSV文件,然後打開該文件CSVExcel

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]) 
+0

謝謝你的回答! – Zeno