簡體   English   中英

在Python 3中將dicts列表轉換為CSV

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

我得到了一個不同長度甚至不同(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文件。 如果key不在當前字典中,則設置默認值(例如' - ')。 示例中的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 = 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標題並按鍵填充值?

使用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

要克服該錯誤,您可以在寫入文件之前收集所有密鑰,如下所示:

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為缺失的鍵指定默認值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM