2017-06-02 4 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

を –

答えて

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インストールが必要です。更新できない場合は、f'list{i}の代わりに'list{}'.format(i)を使用してください。

+0

ありがとうございました! – Zeno

0

おそらく最も簡単な方法は、それが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]) 
+0

答えをありがとう! – Zeno

関連する問題