简体   繁体   中英

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 printed. Here are my codes:

import csv
class Employee(object):
    def main(self,name,idno,position,salary):

        self.name=name
        self.idno=idno
        self.position=position
        self.salary=salary

class Employees(Employee):
    def main (self,name,idno,position,salary,age):
        Employee.main(self,name,idno,position,salary)
        self.age=age

    def input(self):

        e1=[]

        n=int(raw_input("Enter the number of employees:"))
        for i in range(n):
            self.name=raw_input("Name:")
            self.idno=raw_input("Idno:")
            self.position=raw_input("Position:")
            self.salary=int(raw_input("Salary:"))
            e2={"Name":self.name,"Idno":self.idno,"Position":self.position, "Salary":self.salary}
            e1.append(e2)
            print e1

both list of dict to dict or dict of dict conversion doesnt works and writing to csv doesnt works. Can anyone help me out??

My output should look like this:

Name  Idno  Position  Salary
Abc    101   Trainee  12000
Def    102   Trainee  12000

use csv module of python.

data_list = [{...},{...}...]

keys = data_list[0].keys()
with open('test.csv', 'wb') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(data_list)

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 in dict.keys():
    output.append([m,dict[m]])
output2=[]

for n in output:  
    temp=[]
    for k in n:  
        if isinstance(k,list):   #if it's a list
            for j in k:   #for the items of that list
                if isinstance(j,list):   #if it's a list
                    for 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 in range(0,len(output2)):
    for j in range(0,len(output2[i])):
        sheet.cell(row=i+3, column = j+1).value = str(output2[i][j])
wb.save('output.xlsx')
wb.close()   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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