Home > Mobile >  Python: List of dictionaries - using keys as headers & rows are the values (Naive way)
Python: List of dictionaries - using keys as headers & rows are the values (Naive way)

Time:10-14

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

CodePudding user response:

You can do this. First write the keys from any dict in the list.

Then, iterate over the list and write the values line by line.

 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()

My output is,

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

CodePudding user response:

You can do like this,

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")

CodePudding user response:

# 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,key3\nvalue1,value2,value3\nvalue4,value5,value6'

Then you can just write that to disk:

with open("some_file.csv", 'w') as f:
   f.write(final)

CodePudding user response:

Here is a solution using 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 is a file named "output.csv", which contains:

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

CodePudding user response:

You can use this for your case. This might be work.

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()
  • Related