【发布时间】:2019-04-11 00:13:44
【问题描述】:
我得到了一个不同长度的字典列表,甚至不同的(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 应该是这样的:
我正在为我的字典列表尝试此代码,但它返回错误:
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 的标题并按键填充值?
【问题讨论】:
-
您可以使用
pandas.from_dict()方法,循环添加每一行并使用df.to.csv(path_to_csv)保存
标签: python python-3.x list csv dictionary