簡體   English   中英

從 python 中的不規則字典列表創建 CSV

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

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