简体   繁体   中英

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!

csv.DictWriter

csv module provides a DictWriter class which is best suited when we are dealing with records ie 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

You can fix it by first writing header and then writing data for each row.

writer.writerow(csvdata[0].keys())
for i in csvdata:
    writer.writerow(i.values())

convertedtocsv = output.getvalue()
print(convertedtocsv)

Working in a serializer, in which I have to send the data as string but as csv, I got this conversion, if it helps anyone

to_csv = [
    {'name': 'bob', 'age': 25, 'weight': 200},
    {'name': 'jim', 'age': 31, 'weight': 180},
]

keys = to_csv[0].keys()

result = [list(keys)] + [list(row.values()) for row in to_csv]
# [['name', 'age', 'weight'], ['bob', 25, 200], ['jim', 31, 180]]

str_result = '\n'.join([';'.join(str(val) for val in row) for row in result])
# 'name;age;weight\nbob;25;200\njim;31;180'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM