简体   繁体   English

如何将字典列表写为csv

[英]How to write list of a dictionary as csv

I have a dictionary, in which for each key exists lists of (possible empty) lists. 我有一本字典,其中每个键都有(可能为空)列表的列表。 Now I want to write them in a csv file. 现在,我想将它们写入一个csv文件中。

Dictionary: 字典:

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

Furthermore I know that the first list of 'A' is related to the first list of 'B', the second of 'A' to the second of 'B' and so on. 此外,我知道“ A”的第一个列表与“ B”的第一个列表相关,“ A”的第二个与“ B”的第二个列表相关,依此类推。 Wished Output: csv file looking like: 输出结果:csv文件如下所示:

A , B 
a , c
b , d

a , e
t ,
c , 

  , f
  , g

a , c
b , d
  , e

All I tried so far was super "inconvenient" and didn't work in the end. 到目前为止,我所尝试的一切都是超级“不便”,并且最终没有奏效。

I have modified you Dic variable to look like this so that it is valid: 我已经修改了您的Dic变量,使其看起来像这样,以便有效:

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

The following code will do the pair wise matching you want over the elements of the list in each dict entry. 以下代码将在每个字典条目中的列表元素上进行想要的成对配对。

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 is the magic sauce here. zip_longest是这里的魔术酱。 It does the pair wise matching that you want. 它会执行您想要的成对配对。 It will terminate when the end of the longest list is reached (as opposed to just zip which will terminates when the end of the shortest list is reached. 它会在到达最长列表的末尾时终止(而zip会在到达最短列表的末尾时终止。

Content of file.csv: file.csv的内容:

A , B
a , c
b , d

a , e
t , 
c , 

 , f
 , g

a , c
b , d
 , e

A hand made solution, with pure python tools : 手工制作的解决方案,使用纯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

For 对于

A,B
a,c
b,d

a,e
t, 
c, 

 ,f
 ,g

a,c
b,d
 ,e

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM