2017-03-27 1 views
0

idno, name, position 및 salary와 같은 다양한 세부 사항을 가진 n 사용자 입력에 대한 직원 데이터베이스를 만들었습니다. 직원 데이터베이스는 파이썬에서 완벽하게 작동하지만 난 때 여기사용자 입력을위한 dict의 dict

내 코드입니다 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 내가하려고 해요

{idno: {name,position,salary}} 

과 같아야합니다 dict의 dict을 반복 한 다음 csv에 기록합니다. csv로 중첩 된 dict을 작성하는 더 쉬운 방법을 얻을 수 있다면 좋을 것입니다. 루프에 사용

내 CSV 출력해야

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

코드에서 잘못된 결과가 나옵니까? 나에게 잘 어울린다. – jknupp

답변

1

두 점

당신이 당신의 값을 기록하는 선에서
  • ,

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

변수 values이고 내가받은 것 ESS 내부는 헤더 작성하는 파이썬 csv.DictWriter()value

,

{'Idno':keys,'Name':values['Name'],'Position':values["Position"], 'Salary':values["Salary"]} 
  • CSV로 DICT를 작성하는

    로 만들기 사용이다.

    입니다
    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

사전을 사용하면서 출력 CSV 파일을 사용하려면 csv.DictWriter()을 사용하는 것이 좋습니다. 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()

관련 문제