我已經創建了一個員工數據庫的n個用戶輸入與IDNO,名稱,職位和工資等各種細節。員工數據庫完全在蟒蛇但是當我嘗試把它寫爲CSV詞典的字典對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"]})
我的字典的字典應該像
{idno: {name,position,salary}}
我試着迭代字典的字典,然後寫入csv。如果我能以更簡單的方式將嵌套字典編寫爲csv,那將是一件好事。
我的CSV輸出應該
Idno Name Position Salary
101 Abc Trainee 12000
102 Def Fresher 8000
時需要添加ID號。您擁有的代碼(第二個循環)是否會產生不正確的結果?對我來說看起來很好。 – jknupp