如何删除从字典生成的csv文件中的列表括号?

问题描述 投票:-1回答:1

我正在尝试类似的东西 -

sample={"name":["age","number","email"]}
#dictionary stores the relevant data in above format
with open('selected.csv','w') as csvf:
[csvf.write('{0},{1}\n'.format(key,value)) for key,value in 
sample.items()]

#writing data in a csv file with my formatting
"Aaron",[21,020303030,"[email protected]"]

#csv file sample entry

一切正常但CSV文件显示列表括号,我该如何删除它们?

python-3.x list csv dictionary formatting
1个回答
0
投票

如果您使用标准库csv模块,这并不困难:

import csv

sample={"name":["age","number","email"]}
with open('selected.csv', 'w+', newline='') as csvf:
    writer = csv.writer(csvf)
    for k, v in sample.items():
        writer.writerow([k, *v])  # unpack v into a list with k

这将产生一行文件:

name,age,number,email
© www.soinside.com 2019 - 2024. All rights reserved.