[英]Create CSV from irregular list of dictionaries in python
我有一个字典列表,例如
[
{'AB Code': 'Test AB Code', 'Created': '2020-08-04 13:20:55.196500+00:00'},
{'AB Code': 'Test AB Code', 'Created': '2020-08-04 13:20:11.315136+00:00', 'Name': 'John Doe', 'Email': 'john@example.com', 'Phone No.': '1234567890', 'Age': '31'}
]
这两个字典对象有不规则的键。 我想为它下面的每个新键和值创建一个 header 。
结果 CSV 应该是
AB Code, Created, Name, Email, Phone No., Age
Test AB Code, 2020-08-04 13:20:55.196500+00:00, '', '', '', ''
Test AB Code, 2020-08-04 13:20:55.196500+00:00, John Doe, john@example.com, 1234567890, 31
我正在做的是
# header
d_ = []
# values
for index, item in enumerate(data):
if index == 0:
d_.append(list(item.keys()))
d_.append(list(item.values()))
# Add to CSV
buffer = io.StringIO()
wr = csv.writer(buffer, quoting=csv.QUOTE_ALL)
wr.writerows(d_)
生成 CSV
AB Code, Created
Test AB Code, 2020-08-04 13:20:55.196500+00:00, '', '', '', ''
Test AB Code, 2020-08-04 13:20:55.196500+00:00, John Doe, john@example.com, 1234567890, 31
在问题的评论中,@bigbounty 提供了使用pandas
的答案。 这是仅使用标准库的解决方案
import csv
from collections import ChainMap
data = [
{'AB Code': 'Test AB Code', 'Created': '2020-08-04 13:20:55.196500+00:00'},
{'AB Code': 'Test AB Code', 'Created': '2020-08-04 13:20:11.315136+00:00', 'Name': 'John Doe', 'Email': 'john@example.com', 'Phone No.': '1234567890', 'Age': '31'}
]
keys = list(ChainMap(*data))
with open('spam.csv', 'w', newline='') as f:
wrtr = csv.DictWriter(f, fieldnames=keys, quoting=csv.QUOTE_ALL)
wrtr.writeheader()
wrtr.writerows(data)
还有关于合并 dicts 的扩展讨论,这可能有些相关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.