用户输入的dict到csv的d​​ict

时间:2017-03-27 06:36:42

标签: python csv dictionary nested iteration

我为n个用户输入创建了一个员工数据库,其中包含idno,name,position和salary等各种详细信息。员工数据库在python中完美运行,但当我尝试将其写为csv

以下是我的代码:

import csv
d={}
d1={}

n=int(raw_input("Enter the number of employees :"))
for i in range(n):
    emp_name=raw_input("Enter the name of employee :")
    emp_idno=raw_input("Enter the idno of employee :")
    emp_position=raw_input("Enter the position of employee :")
    emp_salary=int(raw_input("Enter the salary of employee :"))

    d1={emp_idno: {"Name": emp_name, "Position":emp_position, "Salary":emp_salary}}
    d.update(d1)
    print d

for key,value in d.iteritems():
    print key,value

    with open('12file1.csv','w') as f:
        w = csv.writer(f)
        w.writerow(['Idno','Name','Position', 'Salary'])
        w.writerows(d.iteritems())

with open('12file1.csv','w') as f:
    w = csv.writer(f)
    w.writerow(['Idno','Name','Position', 'Salary'])
    for keys, values in d.iteritems():
        w.writerows({'Idno':key,'Name':value['Name'],'Position':value["Position"], 'Salary':value["Salary"]})   

我的dict dict应该看起来像

{idno: {name,position,salary}}

我正在尝试迭代dict的dict,然后将其写入csv。如果我能以更简单的方式将嵌套的dict编写为csv,那将会很棒。

我的csv输出应为

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

2 个答案:

答案 0 :(得分:1)

两点

  • 在您编写值的行中,

     w.writerows({'Idno':key,'Name':value['Name'],'Position':value["Position"], 'Salary':value["Salary"]})
    

循环中使用的变量是values,您在里面访问的变量是value

{'Idno':keys,'Name':values['Name'],'Position':values["Position"], 'Salary':values["Salary"]}
  • 将dict写入csv,

利用python csv.DictWriter()为你写标题。

with open('12file1.csv','w') as f:
    w = csv.DictWriter(f,fieldnames=['Idno','Name','Position', 'Salary'])
    w.writeheader()
    for keys,values in d.iteritems():
        w.writerow({'Idno':keys,'Name':values['Name'],'Position':values["Position"], 'Salary':values["Salary"]})                    

即,

import csv
d={}
d1={}

n=int(raw_input("Enter the number of employees :"))
for i in range(n):
    emp_name=raw_input("Enter the name of employee :")
    emp_idno=raw_input("Enter the idno of employee :")
    emp_position=raw_input("Enter the position of employee :")
    emp_salary=int(raw_input("Enter the salary of employee :"))

    d1={emp_idno: {"Name": emp_name, "Position":emp_position, "Salary":emp_salary}}
    d.update(d1)
    print d

for key,value in d.iteritems():
    print key,value

with open('12file1.csv','w') as f:
    w = csv.DictWriter(f,fieldnames=['Idno','Name','Position', 'Salary'])
    w.writeheader()
    for keys,values in d.iteritems():
        w.writerow({'Idno':keys,'Name':values['Name'],'Position':values["Position"], 'Salary':values["Salary"]})                    

希望它有所帮助!

答案 1 :(得分:1)

当您使用词典时,使用csv.DictWriter()处理输出CSV文件会更有意义。使用CSV库时,应始终使用二进制模式下的文件打开,因此要编写需要wb格式的文件,否则最终会在文件中留下额外的空白行。

以下内容可为您提供所需内容:

import csv

d = {}
d1 = {}

n = int(raw_input("Enter the number of employees: "))

for i in range(n):
    emp_name = raw_input("Enter the name of employee: ")
    emp_idno = raw_input("Enter the idno of employee: ")
    emp_position = raw_input("Enter the position of employee: ")
    emp_salary = int(raw_input("Enter the salary of employee: "))

    d1 = {emp_idno: {"Name": emp_name, "Position":emp_position, "Salary":emp_salary, "Idno":emp_idno}}
    d.update(d1)
    print

with open('12file1.csv','wb') as f:
    w = csv.DictWriter(f, fieldnames=['Idno', 'Name', 'Position', 'Salary'])
    w.writeheader()

    for idno, employee in d.iteritems():
        w.writerow(employee)

请注意,由于您将条目保存为词典,因此不会保留订单。使用字典列表而不是词典字典可能更有意义。注意,我在字典中添加了ID号作为键,否则在执行writerow()时需要添加