在python中将dict列表转换为csv

时间:2017-03-31 10:38:10

标签: python list csv dictionary inheritance

我已将继承用于员工详细信息,我正在尝试将其编写为csv。我的输出是以dicts列表的形式,当我尝试将其写为csv时,它不会被打印出来。 这是我的代码:

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
dict dict to dict dict dict dict list of dict转换不起作用,写csv不起作用。任何人都可以帮助我吗?

我的输出应如下所示:

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

2 个答案:

答案 0 :(得分:3)

使用python的csv模块。

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)

答案 1 :(得分:0)

解决方案的一部分是将字典转换为列表...以下处理字典中列表中的列表时的情况...输出位于名为' output'的excel文件中。而不是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()