【发布时间】:2018-10-19 03:06:53
【问题描述】:
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}]}
大家好,我的代码有问题,因为我正在尝试打印一个字典,该字典将以工人的工作名称为键,值将是他们的姓名和薪水(所需的输出是最后的注释行在上面的代码中)。我遇到了一个问题,如果两个或更多人有相同的工作,它将覆盖前一个人的个人资料。因此,如果 John 和 Nick 都是护士,则只会显示 Nick 的个人资料,因为他是用户的最后输入。提前感谢您的帮助!
【问题讨论】:
-
查看
defaultdict。将默认值设置为list和append键值。 -
@roganjosh 除了 defaultdict 还有其他方法吗?
-
是的,检查一个值是否已经存在。如果是,则存储现有值,将现有值附加到您为键分配的新空列表中,然后附加新值。第 3 次遇到相同的键时,检查是否有存储在该键上的列表并适当处理。为什么要避开
defaultdict?
标签: python python-3.x list dictionary