在Python中将字典列表转换为CSV [英] Convert list of dict to csv in python

查看:1077
本文介绍了在Python中将字典列表转换为CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将继承用于员工详细信息,而我正尝试将其编写为csv.我的输出采用字典列表的形式,当我尝试将其编写为csv时,不会输出. 这是我的代码:

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

到dict的dict列表或dict转换的dict都不起作用,并且对csv的写入均不起作用.谁能帮我吗?

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

我的输出应如下所示:

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

推荐答案

使用python的csv模块.

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)

这篇关于在Python中将字典列表转换为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆