2017-10-11 3 views
0
私は各キーのために(可能な空の)リストのリストを存在する辞書を、持っている

として辞書のリストを書き込みます。 これをcsvファイルに書きたいと思います。はどのようにCSV

辞書:

d = {'A' : [['a', 'b'], ['a', 't', 'c']],[[],['a','b']] 
    'B' : [['c', 'd'], ['e']],[['f', 'g'], ['c', 'd', 'e']]} 

さらにI「はA」の最初のリストは「B」、「B」の第2の「A」の第二などの最初のリストに関連していることを知っていますに。 ベストセラー出力:のように見える csvファイル:

A , B 
a , c 
b , d 

a , e 
t , 
c , 

    , f 
    , g 

a , c 
b , d 
    , e 

私がこれまで試したすべてのスーパー「不便」だったと最終的には動作しませんでした。

+0

の場合は、それPOSSですあなたの出力ファイルに適した別のフォーマットを使用することができますか? JSONのように – CHURLZ

+3

'Dic'変数を修正してください。有効なpython dictではありません。 –

+0

辞書変数を編集しました。 @CHURLZ Unfortunalyが、私は今のCSVを必要とする... – Philipp

答えて

1

私はそれが有効であるように、このように見えるようにあなたのディック変数を変更した:

d = {'A' : [['a', 'b'], ['a', 't', 'c'],[],['a','b']], 
    'B' : [['c', 'd'], ['e'],['f', 'g'], ['c', 'd', 'e']]} 

次のコードは、賢明各辞書のエントリにリストの要素の上にあなたがしたいのマッチングペアを行います。

import itertools 

with open('file.csv', 'w') as fid:    
    fid.write("{} , {}\n".format(*d.keys())) 
    # first let's iterate over the element in the lists in d['a'] and d['b'] 
    # A and B will be matched sublists 
    for A, B in itertools.zip_longest(d['A'],d['B'], fillvalue=''): 
     # next iterate over the elements in the sub lists. 
     # Each pair will be an entry you want to write to your file 
     for pair in itertools.zip_longest(A, B, fillvalue=''):       
      fid.write("{} , {}\n".format(*pair)) 
     fid.write('\n') 

zip_longestここでは魔法のソースです。それはあなたが望むペアワイズマッチングを行います。それはちょうどzip最短リストの最後に達した場合に終了する先は対照的に、最も長いリストの最後に(到達したときに終了しますfile.csvになりの

コンテンツ:。手

A , B 
a , c 
b , d 

a , e 
t , 
c , 

, f 
, g 

a , c 
b , d 
, e 
+0

は、私がこれまでzip_longestを知りませんでした 、ありがとうございます。 コード内のコメントもありがとうございます! – Philipp

0

純粋なPythonのツールを使用して作られたソリューション、:

Dic = {'A' : [['a', 'b'], ['a', 't', 'c'],[],['a','b']], 
     'B' : [['c', 'd'], ['e'],['f', 'g'], ['c', 'd', 'e']]} 


with open('out.csv','w') as f: 
    print(*Dic,sep=',',file=f) # keys 
    for A,B in zip(*Dic.values()): 
     for i in range(max(len(A),len(B))): 
      print(A[i] if i<len(A) else ' ',end=',',file=f) 
      print(B[i] if i<len(B) else ' ',  file=f) 
     print(file=f) # blank line 

A,B 
a,c 
b,d 

a,e 
t, 
c, 

,f 
,g 

a,c 
b,d 
,e 
関連する問題