Python3-如何更新字典,使其在一个键中有多个值?

Python3-如何更新字典,使其在一个键中有多个值?,python,python-3.x,list,dictionary,Python,Python 3.x,List,Dictionary,大家好,我的代码有一个问题,因为我试图打印一个字典,该字典将由工人的工作名称键入,值将是他们的姓名和工资(所需的输出是上面代码中的最后一个注释行)。我遇到了一个问题,如果两个或两个以上的人有相同的工作,它将覆盖前一个人的个人资料。比如说,如果John和Nick都是护士,只有Nick的个人资料会显示出来,因为他是用户最后输入的。提前感谢您的帮助 我会这样做: employeenum = int(input("How many employees? ")) employee ={} namelist

大家好,我的代码有一个问题,因为我试图打印一个字典,该字典将由工人的工作名称键入,值将是他们的姓名和工资(所需的输出是上面代码中的最后一个注释行)。我遇到了一个问题,如果两个或两个以上的人有相同的工作,它将覆盖前一个人的个人资料。比如说,如果John和Nick都是护士,只有Nick的个人资料会显示出来,因为他是用户最后输入的。提前感谢您的帮助

我会这样做:

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}]}

尝试以下操作,或者您可以查看
defaultdict

employee = dict()
for i in range(int(input("How Many Employees?"))):
    title = input("Please enter the job's name here: ").lower()
    data = {'Name': input("Please enter the employee's name here: "),
            'Salary': int(input("Please enter the employee's salary here: "))}
    try:
        employee[title].append(data)
    except KeyError:
        employee[title] = [data]
    print(title + ": " + str(data))
print(employee)

简而言之,字典只能返回单个对象,但该对象可以是数组

  • 设置字典以返回员工记录列表。您可以使用上面的meow评论来完成此操作
  • 查找要存储和返回的唯一内容,如员工编号或职务id。您可能有一个员工记录字典,按编号查找,而您当前的字典将查找具有该职务id的所有员工。也就是说,第一个字典的值可以是要在第二个字典中查找的关键字列表
  • 确切的答案取决于你想做什么。你应该决定像“程序员”这样的标题是否可以有两个不同的“约翰·史密斯”来处理。如果这是一个工资比较工具,约翰可能有两份兼职工作,两份工资,但你想把他的英语文学博士学位放在一个地方

找出正确的数据结构方法大约是专业计算机程序员日常工作的一半。不要放弃

查看一下
defaultdict
。将默认值设置为
列表
,只需将值附加到键上即可。@roganjosh除了defaultdict之外,还有其他方法可以执行此操作吗?是的,检查值是否已经存在。如果存在,则存储现有值,将现有值附加到针对键指定的新空列表中,然后结束新值。在第三次遇到相同的密钥时,检查是否有针对该密钥存储的列表,并进行适当的处理。为什么要避免使用默认dict?
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]