2017-10-11 88 views
0

我有一本字典,其中每个键都存在(可能为空)列表的列表。 现在我想将它们写入一个csv文件。如何将字典的列表写为csv

词典:

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

此外我知道“A”的第一列表是与“B”,“A”的第二至的“B”的第二等的第一列表上。 祝愿输出: 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字典。 –

+0

我编辑了字典变量。 @CHURLZ不幸我现在需要一个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 
相关问题