如何将字典列表写为csv

时间:2017-10-11 16:07:25

标签: python list csv dictionary

我有一个字典,其中每个键都存在(可能为空的)列表的列表。 现在我想在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

到目前为止我所做的一切都是超级的,不方便的#34;并且最终没有工作。

2 个答案:

答案 0 :(得分:1)

我修改了你的Dic变量,使其有效:

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

以下代码将对每个dict条目中列表元素进行成对匹配。

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

答案 1 :(得分: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
相关问题