Reputation: 346
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!
Upvotes: 4
Views: 6689
Reputation: 146
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(f'"{str(val)}"' for val in row) for row in result])
# '"name";"age";"weight"\n"bob";"25";"200"\n"jim";"31";"180"'
Upvotes: 0
Reputation: 71689
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
Upvotes: 6
Reputation: 563
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)
Upvotes: 1