Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将具有不匹配键的词典列表转储到csv文件中_Python_Csv_Dictionary - Fatal编程技术网

Python 将具有不匹配键的词典列表转储到csv文件中

Python 将具有不匹配键的词典列表转储到csv文件中,python,csv,dictionary,Python,Csv,Dictionary,询问如何将字典列表(带有匹配键)转储到csv文件中 我的问题与此类似,但我假设字典不一定有匹配的键:在这种情况下,我希望该单元格不带任何值(或分配None/0/)。下面的例子 csv模块中是否有允许我执行此操作的实用程序 在肯定的情况下,我该怎么做 在否定的情况下,我是否应该收集所有键,然后检查所有字典,并将缺少的键的值设置为None/0/ 范例 to_csv = [{'name':'bob','age':25,'weight':200, 'height':181}, {

询问如何将字典列表(带有匹配键)转储到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
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])