在python中将dict列表转换为csv

8yparm6h  于 2023-03-05  发布在  Python
关注(0)|答案(2)|浏览(174)

我已经使用继承的雇员详细信息,我试图写它作为一个csv.我的输出是在一个字典列表的形式,当我试图写它作为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或dict的dict转换不工作,写到csv不工作。有人能帮我吗?
我的输出应该如下所示:

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

efzxgjgh1#

使用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)
ejk8hzay

ejk8hzay2#

解决方案的一部分是将您的字典转换为列表...下面处理的情况下,您有列表中的列表在字典中...输出是在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()

相关问题