[英]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.