我目前的任务是从字典列表中创建一个CSV文件,其中标题是dic键,行是dic值
Ex。
dictionary_list = [{ 'key1': 'value1', 'key2: 'value2', 'key3': 'value3'}, {'key1': 'value4', 'key2: 'value5', 'key3': 'value6'}]
输出将是CSV文件:
key1,key2,key3
value1,value2,value3
value4,value5,value6
我们不允许使用dictwritter/csv/panda,而且必须以天真的方式使用
我目前已经收集了密钥,但正在努力拆分值,这样它就不会在同一行打印出所有值,而是在新行中写入第二个字典值:
我的获取值代码:
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
您可以这样做。首先写下列表中任意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
你可以这样做,
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")
# 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,key3nvalue1,value2,value3nvalue4,value5,value6'
然后你可以把它写到磁盘上:
with open("some_file.csv", 'w') as f:
f.write(final)
以下是使用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")
输出是一个名为"的文件;输出.csv";,其中包含:
key1,key2,key3
value1,value2,value3
value4,value5,value6
您可以将其用于您的案例。这可能是工作。
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()