简体   繁体   English

使用 dict_keys 将 dict 列表转换为 CSV 字符串

[英]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.我正在尝试将字典列表转换为 lambda function 的 csv 字符串。 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.我正在尝试重新编写它,以便它基于 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' output: '"fruit","apple"\r\n"count","1"\r\n"color","red"\r\n"fruit","banana"\r\n"count" ,"2"\r\n"颜色","黄色"\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.我知道这可以使用 .to_csv 方法在 pandas 中实现。 but i just wanted to try it without pandas or any 3rd party libraries.但我只是想在没有 pandas 或任何第三方库的情况下尝试它。

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 csv模块提供了一个DictWriter class 最适合我们处理记录时,即需要写入 csv 文件的字典列表

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.您可以通过首先写入 header 然后为每一行写入数据来修复它。

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在序列化程序中工作,我必须将数据作为字符串发送,但作为 csv,我得到了这个转换,如果它对任何人都有帮助

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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