我有一个字典列表,其中的值是列表。我想将其写入csv文件,同时删除[]。但是,当我运行以下代码时,它会写到csv中,但保留[]。没有它怎么写?
data_list_of_dx = [{'a_id':['NC01'],'org_id':['FX0'],'status':['Active','Current']}, {'a_id':['bC01'],'org_id':['dr0'],'status':['Dormant','Current']},{'a_id':['NC02'],'org_id':['TX0'],'status':['Active','Late']}, {'a_id':['ty01'],'org_id':['t00r0'],'status':['New','Current']}]
fieldnames = ['a_id','org_id','status']
g_n = 'test_ct_data_2.csv'
g = open( g_n , 'w', encoding = 'utf-8' , newline ='')
writer = csv.DictWriter( g , fieldnames = fieldnames )
writer.writeheader()
for row in data_list_of_dx:
writer.writerow(row)
g.close()
答案 0 :(得分:1)
在将dict的值写入csv之前,可以在其值上使用str.join
。
例如:
data_list_of_dx = [{'a_id':['NC01'],'org_id':['FX0'],'status':['Active','Current']}, {'a_id':['bC01'],'org_id':['dr0'],'status':['Dormant','Current']},{'a_id':['NC02'],'org_id':['TX0'],'status':['Active','Late']}, {'a_id':['ty01'],'org_id':['t00r0'],'status':['New','Current']}]
fieldnames = ['a_id','org_id','status']
g_n = 'test_ct_data_2.csv'
g = open( g_n , 'w', encoding = 'utf-8' , newline ='')
writer = csv.DictWriter( g , fieldnames = fieldnames )
writer.writeheader()
for row in data_list_of_dx:
val = dict((k, ",".join(v)) for k, v in row.items())
writer.writerow(val)
g.close()
with open()
例如:with open( g_n , 'w', encoding = 'utf-8' , newline ='') as g: