如何将词典列表写成cs

2024-06-02 04:25:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典,里面每个键都有一个(可能是空的)列表。 现在我想把它们写在一个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

到目前为止,我所尝试的都是超级“不方便”,最终没有奏效。你知道吗


Tags: 文件csv列表字典词典奏效
2条回答

使用纯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

我已将您的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是这里的神奇酱汁。它进行你想要的成对匹配。它将在到达最长列表的末尾时终止(而不是在到达最短列表的末尾时终止)。你知道吗

的内容文件.csv地址:

A , B
a , c
b , d

a , e
t , 
c , 

 , f
 , g

a , c
b , d
 , e

相关问题 更多 >