Convert List Of Dict To Csv In Python
I have used inheritance for employee details and I'm trying to write it as a csv. My output is in the form of list of dicts and when I'm trying to write it as csv, its not getting
Solution 1:
use csv
module of python.
data_list = [{...},{...}...]
keys = data_list[0].keys()
withopen('test.csv', 'wb') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(data_list)
Solution 2:
Part of the solution is converting your dictionary to a list...The following handles the situation when you have lists within lists within a dictionary...The output is in excel file named 'output' rather than csv.
output=[]
for m indict.keys():
output.append([m,dict[m]])
output2=[]
for n in output:
temp=[]
for k in n:
ifisinstance(k,list): #if it's a listfor j in k: #for the items of that listifisinstance(j,list): #if it's a listfor i in j: #for the items of that list
temp.append(i)
else:
temp.append(j)
else:
temp.append(k) #if it's not a list, just append
output2.append(temp) #append the overall#%%#output to excel
wb=openpyxl.load_workbook('output.xlsx')
sheet=wb.get_sheet_by_name('Sheet1')
for i inrange(0,len(output2)):
for j inrange(0,len(output2[i])):
sheet.cell(row=i+3, column = j+1).value = str(output2[i][j])
wb.save('output.xlsx')
wb.close()
Post a Comment for "Convert List Of Dict To Csv In Python"