Skip to content
Advertisement

Python: List of dictionaries – using keys as headers & rows are the values (Naive way)

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.

dictionary_list = [{ 'key1': 'value1', 'key2: 'value2', 'key3': 'value3'}, {'key1': 'value4', 'key2: 'value5', 'key3': 'value6'}]

Output would be a CSV File:

key1,key2,key3
value1,value2,value3
value4,value5,value6

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:

v = [x for y in dictionary_list for x in y.values()]
finalV = ','.join(str(x) for x in v)

My current file output:

key1,key2,key3
value1,value2,value3,value4,value5,value6

Advertisement

Answer

# 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

At this point, final is a comma delimited string:

'key1,key2,key3nvalue1,value2,value3nvalue4,value5,value6'

Then you can just write that to disk:

with open("some_file.csv", 'w') as f:
   f.write(final)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement