2016-04-09 14 views
0

私はタプルのリストを含んでいる辞書「allData」を持っています。辞書内のタプルリストをcsvに書き込む

allData = {'Shirts': [(69.95, 1), (52.45, 2), (99.95, 3), (79.95, 4), (79.95, 5)], 
      'Jeans': [(70.0, 1), (50.0, 2), (99.0, 3), (79.95, 4), (80.0, 5)]} 

各キーとその要素をcsvファイルに書きたいと思います。

def writeCSV(path, filename, d): 
    filename = path + filename 

    with open(filename, 'wb') as outfile: 
     writer = csv.writer(outfile, delimiter='~') 
     writer.writerow(d.keys()) 
     writer.writerows(izip_longest(*d.values())) 

    print "write file complete" 

writeCSV("C:\\Projects\\Output", "output.csv", allData) 

これは私のシャツとジーンズは列がAとB

Shirts  Jeans 
(69.95, 1) (49.95, 1) 
(52.45, 2) (0.0, 2) 
(99.95, 3) (104.95, 3) 
(79.95, 4) (59.95, 4) 
(79.95, 5) (80.0, 5) 

これが出力されているExcelで次の出力を与える:次のように

私がこれまで持っているコードです。私は実際にシャツ、イド、ジーンズ、IDはそれぞれ列A、B、C、Dである必要があります。

Shirts id Jeans id 
69.95 1 70.0 1 
52.45 2 50.0 2 
99.95 3 99.0 3 
79.95 4 79.95 4 
79.95 5 80.0 5 

ご協力いただきまして誠にありがとうございます。

答えて

0

もう1つの可能な解決策:

import os 
import csv 

from itertools import izip_longest 

def writeCSV(path, filename, d): 
    def flatten(l): 
     return [t[i] for t in l for i in range(len(t))] 

    filename = os.path.join(path, filename) 

    with open(filename, 'wb') as outfile: 
     writer = csv.writer(outfile, delimiter='~') 
     keys = d.keys() 
     writer.writerow(flatten(zip(keys, ['id'] * len(keys)))) 
     # Keep the values in the same order as keys 
     values = [d[key] for key in keys] 
     writer.writerows(flatten(row) for row in izip_longest(*values, fillvalue=('', ''))) 
     print "write file complete" 

writeCSV("C:\\Projects\\Output", "output.csv", allData) 
0

これは動作します:

不均等なサイズのデータ​​を使用して
import csv 
import os 

def writeCSV(path, filename, d): 
    filename = os.path.join(path, filename) 
    col_names = list(d.keys()) 
    header = [] 
    for name in col_names: 
     header.append(name) 
     header.append('id') 

    with open(filename, 'wb') as outfile: 
     writer = csv.writer(outfile) # change delimiter with `delimiter=' '` 
     writer.writerow(header) 
     index = 0 
     end = max([len(x) for x in d.values()]) 
     while index < end: 
      line = [] 
      for name in col_names: 
       try: 
        row_values = d[name][index] 
       except IndexError: 
        row_values = [''] * len(col_names) 
       line.extend(row_values) 
      writer.writerow(line) 
      index += 1 

csv_output.csv

allData = {'Shirts': [(69.95, 1), (52.45, 2), (99.95, 3), (79.95, 4), (79.95, 5)], 
      'Jeans': [(70.0, 1), (50.0, 2), (99.0, 3), (79.95, 4), (80.0, 5) , (80.0, 5)]} 

writeCSV(os.getcwd(), "csv_output.csv", allData) 

内容:それはもう一つを持っているので、ジーンズのための列が長くなっていることを

Jeans,id,Shirts,id 
70.0,1,69.95,1 
50.0,2,52.45,2 
99.0,3,99.95,3 
79.95,4,79.95,4 
80.0,5,79.95,5 
80.0,5,, 

注意を入力辞書のデータセット。

関連する問題