【问题标题】:Python 3 - How to update dictionary to have multiple values in one key?Python 3 - 如何更新字典以在一个键中包含多个值?
【发布时间】: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。将默认值设置为 listappend 键值。
  • @roganjosh 除了 defaultdict 还有其他方法吗?
  • 是的,检查一个值是否已经存在。如果是,则存储现有值,将现有值附加到您为键分配的新空列表中,然后附加新值。第 3 次遇到相同的键时,检查是否有存储在该键上的列表并适当处理。为什么要避开defaultdict

标签: python python-3.x list dictionary


【解决方案1】:

尝试以下方法,或者您可以查看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]

【讨论】:

    【解决方案2】:

    我会这样做:

    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)
    

    【讨论】:

      【解决方案3】:

      简短的回答是字典只能返回一个对象,但该对象可以是一个数组。

      • 设置字典以返回员工记录列表。您可以使用上面喵的评论来做到这一点。
      • 找到一些独特的东西来存储和退回,例如员工编号或工作 ID。您可能有一本员工记录字典,按编号查找,而您当前的字典用于查找具有该职位 ID 的所有员工。也就是说,第一个字典的值可以是要在第二个字典中查找的键列表。
      • 确切的答案取决于您要执行的操作。您应该决定像“程序员”这样的标题是否可以让两个不同的“约翰·史密斯”人一起工作。如果这是一个薪水比较工具,John 可能有两份兼职工作,两份薪水,但您想将他的英国文学博士学位放在一个地方。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-28
        • 2012-03-09
        • 1970-01-01
        • 1970-01-01
        • 2018-06-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多