【问题标题】:Dump list of dictionaries with non-matching keys into csv file将具有不匹配键的字典列表转储到 csv 文件中
【发布时间】:2015-12-15 15:39:59
【问题描述】:

Here 询问如何将字典列表(带有匹配键)转储到 csv 文件中。

我的问题类似,但是我假设字典不一定具有匹配的键:在这种情况下,我想将该单元格保留为没有值(或分配 None/0/..)。下面的例子。

  • csv 模块中是否有允许我执行此操作的实用程序?
  • 在肯定的情况下,我该怎么做?
  • 在否定的情况下,我是否应该收集所有键,然后遍历所有字典并将丢失键的值设置为 None/0/...?

例子

to_csv = [{'name':'bob','age':25,'weight':200, 'height':181},
          {'name':'jim','age':31,'weight':180}]

应该变成:

name,age,weight,height
bob,25,200,181
jim,31,180,None

【问题讨论】:

    标签: python csv dictionary


    【解决方案1】:
    import csv
    
    to_csv = [{'name':'bob','age':25,'weight':200, 'height':181},
              {'name':'jim','age':31,'weight':180}]
    
    # find header
    s = set()
    for i in to_csv:
        s.update(i)
    header = list(s)
    
    with open("foo.csv", 'w') as f:
        writer = csv.writer(f)
        writer.writerow(header)
        for d in to_csv:
            writer.writerow([d.get(i, "None") for i in header])
    

    【讨论】:

      猜你喜欢
      • 2016-01-28
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      • 2021-07-09
      • 2017-04-11
      • 2014-03-01
      • 2019-02-01
      • 1970-01-01
      相关资源
      最近更新 更多