Python 3 - 如何更新字典以在一个键中包含多个值?

标签 python python-3.x list dictionary

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/

相关文章:

python - 如何在Python3中通过for循环时获得严格的单词匹配

Python -- Pygame 属性错误 : int object has no attribute 'draw'

python - 如何在新行上打印Python列表的每个第n个索引?

python - 从 XML 解析名称/值对

python - 在3.8.2上安装kivy python

c++ - c++双向链表的相反元素的成对乘法

r - 根据数据框和列名称创建一个命名的空列表

python - Fhir 史诗沙盒 : Using a JWT to Obtain an Access Token for a Backend Service

python - python pyqt5 类引用

python - 在 Windows 8.1 上的 python 中使用 opencv 和 zbar 来检测二维码