【问题标题】:How to write list of a dictionary as csv如何将字典列表写为csv
【发布时间】:2017-10-11 16:07:24
【问题描述】:

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

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

【问题讨论】:

  • 是否可以为您的输出文件使用另一种更合适的格式?像 JSON
  • 请更正您的Dic 变量,它不是有效的python dict。
  • 我编辑了字典变量。 @CHURLZ 不幸的是,我现在需要一个 csv...

标签: python list csv dictionary


【解决方案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

【讨论】:

  • 谢谢,到目前为止我还不知道 zip_longest。也感谢代码中的cmets!
【解决方案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

【讨论】:

    猜你喜欢
    • 2014-06-17
    • 2016-10-26
    • 2016-03-01
    • 1970-01-01
    • 2014-06-30
    • 2020-05-29
    • 2020-01-13
    • 1970-01-01
    相关资源
    最近更新 更多