我目前的任務是從字典串列中創建一個 CSV 檔案,其中標題是 dic 鍵,行是 dic 值
前任。
dictionary_list = [{ 'key1': 'value1', 'key2: 'value2', 'key3': 'value3'}, {'key1': 'value4', 'key2: 'value5', 'key3': 'value6'}]
輸出將是一個 CSV 檔案:
key1,key2,key3
value1,value2,value3
value4,value5,value6
我們不允許使用 dictwriter/csv/pandas 并且必須以幼稚的方式進行。
我目前已經收集了鍵,但是正在努力嘗試拆分值,以便在新行中寫入第二個字典值,而不是列印出同一行中的所有值:
我的獲取值代碼:
v = [x for y in dictionary_list for x in y.values()]
finalV = ','.join(str(x) for x in v)
我當前的檔案輸出:
key1,key2,key3
value1,value2,value3,value4,value5,value6
uj5u.com熱心網友回復:
你可以這樣做。首先從串列中的任何 dict 中寫入鍵。
然后,遍歷串列并逐行寫入值。
dictionary_list = [{ 'key1': 'value1', 'key2': 'value2', 'key3': 'value3'},
{'key1': 'value4', 'key2': 'value5', 'key3': 'value6'}]
f = open("test.csv", "a")
f.write(','.join(list(dictionary_list[0].keys()))) #write headers
f.write('\n')
for i in dictionary_list:
f.write(','.join(list(i.values()))) #write values
f.write('\n')
f.close()
我的輸出是,
key1, key2, key3
value1, value2, value3
value4, value5, value6
uj5u.com熱心網友回復:
你可以這樣做,
lst = [{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'},
{'key1': 'value4', 'key2': 'value5', 'key3': 'value6'}]
with open("test.csv", "w") as f:
# write header
f.write(f"{','.join(lst[0].keys())}\n")
# write values
for item in lst:
f.write(f"{','.join(item.values())}\n")
uj5u.com熱心網友回復:
# if you know for a fact that all dictionaries have identical keys
keys = ",".join(dictionary_list[0].keys())
values = "\n".join([",".join(v for v in d.values()) for d in dictionary_list])
final = keys "\n" values
# then dump string to csv
此時,final是一個逗號分隔的字串:
'key1,key2,key3\nvalue1,value2,value3\nvalue4,value5,value6'
然后您可以將其寫入磁盤:
with open("some_file.csv", 'w') as f:
f.write(final)
uj5u.com熱心網友回復:
這是使用的解決方案operator.itemgetter:
from operator import itemgetter
dictionary_list = [
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'},
{'key1': 'value4', 'key2': 'value5', 'key3': 'value6'},
]
# Get the keys out of the first dictionary
keys = list(dictionary_list[0].keys())
# Create an itemgetter using the keys
x = itemgetter(*keys)
# Use a context-manager to create a file to write against
with open("output.csv", "w") as csv:
# Write the headers using the keys from the first dictionary
csv.write(",".join(keys) "\n")
# Loop over each dictionary, and use the itemgetter to get the values in the same order.
for i in dictionary_list:
csv.write(",".join(x(i)) "\n")
輸出是一個名為“output.csv”的檔案,其中包含:
key1,key2,key3
value1,value2,value3
value4,value5,value6
uj5u.com熱心網友回復:
您可以將其用于您的情況。這可能是作業。
f = open("demofile.csv", "w")
key = ",".join([*dictionary_list[0]]) '\n'
f.write(key)
for dictionary in dictionary_list:
values = ','.join([val for val in dictionary.values()]) '\n'
f.write(values)
f.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/514425.html
標籤:Python列表文件字典
