简体   繁体   English

从 python 中的不规则字典列表创建 CSV

[英]Create CSV from irregular list of dictionaries in python

I have a list of dictionaries like我有一个字典列表,例如

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

The two dictionary objects have irregular keys.这两个字典对象有不规则的键。 I want to create a header for each new key and values beneath it.我想为它下面的每个新键和值创建一个 header 。

The resultant CSV should be结果 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

What I'm doing is我正在做的是

# 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_)

Which generates CSV生成 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

There is answer using pandas provided by @bigbounty in comments to the question.在问题的评论中,@bigbounty 提供了使用pandas的答案。 Here is solution using just standard library这是仅使用标准库的解决方案

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)

Also there is extended discussion on merging dicts , which may be somewhat relevant.还有关于合并 dicts 的扩展讨论,这可能有些相关。

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

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