Reputation: 3660
I have a list of dictionary where the values are lists. I want to write it to a csv file, while removing the [] . But when I run the following code it writes out to csv, but retains the []. How do I write it without that?
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()
Upvotes: 0
Views: 401
Reputation: 82765
You can use str.join
on the value in your dict before writing it to the csv.
Ex:
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()
Ex: with open( g_n , 'w', encoding = 'utf-8' , newline ='') as g:
Upvotes: 1