Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert list of dict to CSV string using dict_keys

i am trying to convert a list of dict's to csv string for a lambda function. the code i have written below gives data as key value. i am trying to re-write this so that it works based on the dict_keys.

import io
import csv

output = io.StringIO()
csvdata = [{"fruit": "apple", "count": "1", "color": "red"},{"fruit": "banana", "count": "2", "color": "yellow"}]
writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC)
    for i in csvdata:
        for key, value in i.items():
            writer.writerow([key, value])
convertedtocsv = output.getvalue()

output: '"fruit","apple"\r\n"count","1"\r\n"color","red"\r\n"fruit","banana"\r\n"count","2"\r\n"color","yellow"\r\n'

fruit  apple
count  1 
color  red
fruit  banana
count  2
color  yellow

i would want the data in below format

fruit   count  color
apple   1      red
banana  2      yellow

i am aware that this can be achieved in pandas using the .to_csv method. but i just wanted to try it without pandas or any 3rd party libraries.

any help is appreciated. thanks!

like image 1000
rakesh Avatar asked Sep 02 '25 06:09

rakesh


1 Answers

csv.DictWriter

csv module provides a DictWriter class which is best suited when we are dealing with records i.e. list of dictionaries that needs to be written to a csv file

fields = ['fruit', 'count', 'color'] 
writer = csv.DictWriter(output, fieldnames=fields, delimiter='\t')
writer.writeheader()
writer.writerows(csvdata)

print(output.getvalue())

fruit   count   color
apple   1       red
banana  2       yellow
like image 181
Shubham Sharma Avatar answered Sep 04 '25 19:09

Shubham Sharma