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

时间:2017-06-02 17:24:09

标签: python excel python-2.7 dictionary

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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}

答案 2 :(得分:0)

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

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