在Python 3中将字典列表转换为CSV

时间:2018-11-07 14:37:10

标签: python python-3.x list csv dictionary

我得到了具有不同长度甚至不同(key: values)对字典的列表。例如:

[
    {'key1': 'value1', 'key3':'value3'},
    {'key1': 'someValue', 'key2':'value2', 'key3':'value3'},
    {'anotherKey': 'anotherValue', 'key1': 'value1', 'key2':'value2'},
    {'anotherKey': 'anotherValue', 'anotherKey1': 'anotherValue1', 'key1': 'value1', 'key2':'value2', 'key3':'value3'},
]

我需要使用所有键作为标题和值来创建CSV文件。如果键不在当前字典中,则设置默认值(例如'-')。示例中的CSV应该看起来像这样:

enter image description here

我正在尝试将此代码用于我的词典列表,但返回错误:

listOfDicts = [
    {'key1': 'value1', 'key3':'value3'},
    {'key1': 'someValue', 'key2':'value2', 'key3':'value3'},
    {'anotherKey': 'anotherValue', 'key1': 'value1', 'key2':'value2'},
    {'anotherKey': 'anotherValue', 'anotherKey1': 'anotherValue1', 'key1': 'value1', 'key2':'value2', 'key3':'value3'},
]

keys = listOfDicts[0].keys()
with open('test.csv', 'a') as output_file:
    dict_writer = csv.DictWriter(output_file, fieldnames=keys, delimiter='@')
    dict_writer.writeheader()
    dict_writer.writerows(listOfDicts)

错误:

ValueError: dict contains fields not in fieldnames: 'key2'

如何将所有唯一键添加为CSV标头,并按键填充其值?

2 个答案:

答案 0 :(得分:3)

使用DicitWritter() restval参数

  

可选的restval参数指定在以下情况下要写入的值   词典缺少字段名中的键。

,对于fieldnames参数,使用字典列表中所有可用键的列表。

import csv


listOfDicts = [
    {'key1': 'value1', 'key3':'value3'},
    {'key1': 'someValue', 'key2':'value2', 'key3':'value3'},
    {'anotherKey': 'anotherValue', 'key1': 'value1', 'key2':'value2'},
    {'anotherKey': 'anotherValue', 'anotherKey1': 'anotherValue1', 'key1': 'value1', 'key2':'value2', 'key3':'value3'},
]

keys = [i for s in [d.keys() for d in listOfDicts] for i in s]

with open('test.csv', 'a') as output_file:
    dict_writer = csv.DictWriter(output_file, restval="-", fieldnames=keys, delimiter='@')
    dict_writer.writeheader()
    dict_writer.writerows(listOfDicts)

输出:

$ cat test.csv 
key3@key1@key2@anotherKey@anotherKey1
value3@value1@-@-@-
value3@someValue@value2@-@-
-@value1@value2@anotherValue@-
value3@value1@value2@anotherValue@anotherValue1

参考:https://docs.python.org/2/library/csv.html#csv.DictWriter

答案 1 :(得分:1)

要克服该错误,可以在写入文件之前收集所有密钥,如下所示:

keys = set()
for d in listOfDicts:
    keys.update(d.keys())

with open('test.csv', 'a') as output_file:
    dict_writer = csv.DictWriter(
        output_file, fieldnames=keys, restval='-', delimiter='@')
    dict_writer.writeheader()
    dict_writer.writerows(listOfDicts)

您可以使用参数DictWriter.restval为缺少的键分配默认值。