employeenum = int(input("How many employees? "))
employee ={}
namelist = []
salarylist = []
jobname = []
profile = []
for i in range (0,employeenum):
job1 = input("Please enter the job's name here: ").lower()
name1 = input("Please enter the employee's name here: ")
salary1 = int(input("Please enter the employee's salary here: "))
jobname.append(job1)
print(jobname)
namelist.append(name1)
salarylist.append(salary1)
profile.append([{'Name': namelist[i], 'Salary': salarylist[i]}])
employee.update({jobname[i]: profile[i]})
employee[jobname[i]].append(profile[i])
print(employee)
print(profile)
print(employee)
# {'Programmer': [{'Name': 'Tim', 'Salary': 65000}, {'Name': 'Sally', 'Salary': 50500}], 'Part Time Manager': [{'Name': 'Bob', 'Salary': 17500}]}
大家好,我的代码有问题,因为我正在尝试打印一个字典,该字典将以 worker 的工作名称为键,值将是他们的姓名和薪水(所需的输出是最后一行注释在上面的代码中)。我遇到了一个问题,如果两个或更多人拥有相同的工作,它将覆盖前一个人的个人资料。因此,如果 John 和 Nick 都是护士,则只会显示 Nick 的个人资料,因为他是用户最后输入的。在此先感谢您的帮助!
最佳答案
尝试以下操作,或者您可以查看 defaultdict
:
employeenum = int(input("How many employees? "))
employee ={}
for i in range (0, employeenum):
job1 = input("Please enter the job's name here: ").lower()
name1 = input("Please enter the employee's name here: ")
salary1 = int(input("Please enter the employee's salary here: "))
new_entry = {"Name": name1, "Salary": salary1}
if job1 in employee:
employee[job1].append(new_entry)
else:
employee[job1] = [new_entry]
关于Python 3 - 如何更新字典以在一个键中包含多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52880374/