我已經為此苦苦掙扎了一兩天,但我似乎無法做到正確。
project_index = [
{A: ['1', '2', '3']},
{B: ['4', '5', '6']},
{C: ['7', '8', '9']},
{D: ['10', '11', '12']},
{E: ['13', '14', '15']},
{F: ['16', '17', '18']}
]
我已經嘗試了很多不同的方法來嘗試將其放入 .CSV 表中,但它總是以非常不正確的格式出現,例如它們沿對角線平鋪,或者一堆只有鍵的行一遍又一遍(例如:
ABCDEF
ABCDEF
ABCDEF
ABCDEF)
此外,即使我得到了要顯示的值,整個字串陣列也會顯示在一個單元格中。
有什么辦法可以讓每個字典成為一列,陣列值中的每個字串作為所述列中自己的單元格?
例子:

先感謝您!
uj5u.com熱心網友回復:
假設你所有的鑰匙都是獨一無二的......那么這個(稍微修改一下):
project_index = [
{'A': ['1', '2', '3']},
{'B': ['4', '5', '6']},
{'C': ['7', '8', '9']},
{'D': ['10', '11', '12', '20']},
{'E': ['13', '14', '15']},
{'F': ['16', '17', '18']}
]
應該看起來像這樣:
project_index_dict = {}
for x in project_index:
project_index_dict.update(x)
print(project_index_dict)
# Output:
{'A': ['1', '2', '3'],
'B': ['4', '5', '6'],
'C': ['7', '8', '9'],
'D': ['10', '11', '12', '20'],
'E': ['13', '14', '15'],
'F': ['16', '17', '18']}
在這一點上,而不是重新發明輪子......你可以只使用pandas.
import pandas as pd
# Work-around for uneven lengths:
df = pd.DataFrame.from_dict(project_index_dict, 'index').T.fillna('')
df.to_csv('file.csv', index=False)
輸出file.csv:
A,B,C,D,E,F
1,4,7,10,13,16
2,5,8,11,14,17
3,6,9,12,15,18
,,,20,,
csv模塊方法:
import csv
from itertools import zip_longest, chain
header = []
for d in project_index:
header.extend(list(d))
project_index_rows = [dict(zip(header, x)) for x in
zip_longest(*chain(list(*p.values())
for p in project_index),
fillvalue='')]
with open('file.csv', 'w') as f:
writer = csv.DictWriter(f, fieldnames = header)
writer.writeheader()
writer.writerows(project_index_rows)
uj5u.com熱心網友回復:
我的解決方案不使用 Pandas。這是計劃:
- 對于標題行,從字典中獲取所有鍵
- 對于資料行,用于
zip轉置列 -> 行
import csv
def first_key(d):
"""Return the first key in a dictionary."""
return next(iter(d))
def first_value(d):
"""Return the first value in a dictionary."""
return next(iter(d.values()))
with open("output.csv", "w", encoding="utf-8") as stream:
writer = csv.writer(stream)
# Write the header row
writer.writerow(first_key(d) for d in project_index)
# Write the rest
rows = zip(*[first_value(d) for d in project_index])
writer.writerows(rows)
output.csv 的內容:
A,B,C,D,D,F
1,4,7,10,13,16
2,5,8,11,14,17
3,6,9,12,15,18
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/518160.html
標籤:PythonCSV
