I’m currently tasked with creating a CSV file from a list of dictionaries where the headers are the dic keys and the rows the dic values
Ex.
JavaScript
x
2
1
dictionary_list = [{ 'key1': 'value1', 'key2: 'value2', 'key3': 'value3'}, {'key1': 'value4', 'key2: 'value5', 'key3': 'value6'}]
2
Output would be a CSV File:
JavaScript
1
4
1
key1,key2,key3
2
value1,value2,value3
3
value4,value5,value6
4
We’re not allowed to use dictwriter/csv/pandas and have to do it the naïve way.
I currently have the keys gathered, but am struggling with trying to split the values so that instead of printing out all the values in the same line it writes the 2nd dictionary values in a new line:
My getting values code:
JavaScript
1
3
1
v = [x for y in dictionary_list for x in y.values()]
2
finalV = ','.join(str(x) for x in v)
3
My current file output:
JavaScript
1
3
1
key1,key2,key3
2
value1,value2,value3,value4,value5,value6
3
Advertisement
Answer
JavaScript
1
9
1
# if you know for a fact that all dictionaries have identical keys
2
keys = ",".join(dictionary_list[0].keys())
3
4
values = "n".join([",".join(v for v in d.values()) for d in dictionary_list])
5
6
final = keys + "n" + values
7
8
# then dump string to csv
9
At this point, final
is a comma delimited string:
JavaScript
1
2
1
'key1,key2,key3nvalue1,value2,value3nvalue4,value5,value6'
2
Then you can just write that to disk:
JavaScript
1
3
1
with open("some_file.csv", 'w') as f:
2
f.write(final)
3