简体   繁体   English

在Python 3中将dicts列表转换为CSV

[英]Convert list of dicts to CSV in Python 3

I got a list of dictionaries with different length and even different (key: values) pairs. 我得到了一个不同长度甚至不同(key: values)对的词典列表。 For example: 例如:

[
    {'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'},
]

I need to create CSV file with all of keys as headers and values. 我需要创建包含所有键作为标题和值的CSV文件。 If key not in the current dictionary then set the default value (for example '-'). 如果key不在当前字典中,则设置默认值(例如' - ')。 The CSV from example should be looking like that: 示例中的CSV应该看起来像这样:

在此输入图像描述

I'm trying this code for my list of dictionaries, but it returns an error: 我正在为我的字典列表尝试此代码,但它返回一个错误:

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)

ERROR: 错误:

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

How I can add all unique keys as headers for CSV and fill it values by key? 如何将所有唯一键添加为CSV标题并按键填充值?

Use DicitWritter() restval parameter, 使用DicitWritter() restval参数,

The optional restval parameter specifies the value to be written if the dictionary is missing a key in fieldnames. 如果字典缺少字段名中的键,则可选的restval参数指定要写入的值。

and for fieldnames parameter use a list of all available keys in a list of dictionaries. 对于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)

output: 输出:

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

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

To overcome the error, you can collect all the keys before writing the file, like this: 要克服该错误,您可以在写入文件之前收集所有密钥,如下所示:

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)

You can use the parameter DictWriter.restval to assign default values for missing keys. 您可以使用参数DictWriter.restval为缺失的键指定默认值。

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

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