繁体   English   中英

带有循环的Python字典

[英]Python dictionaries with loops

我正在尝试输出以部门标题作为关键字的字典,以及仅以该部门内的员工作为其对应值的字典列表。 我已经关闭了,但是当我运行此功能时,dep_dict将所有部门员工附加到每个键上。 这是在做什么:

{
department1: [{employee A info}, {employee B info}],
department2: [{employee A info}, {employee B info}]
}

#Function for adding employees to dictionary by department
def dep_emp():
    for x in dep_tup:
        for names in employees:
            if x == employees[names]["em_department"]:
                dep_list.append(employees[names])
                dep_dict[x] = dep_list
                continue

但是相反,它应该看起来像这样(如果有两个部门),并假设员工A为部门1工作,员工B为部门2工作:

{
department1: [{employee A info}],
department2: [{employee B info}]
}

注意:dep_tup是用户输入的所有部门名称的元组,雇员是由所有雇员及其信息组成的字典(键=雇员名称)

您可以避免dep_dict[x] = dep_list中的每个name in employees dep_dict[x] = dep_list

您必须为每个部门重置/重新定义dep_list

def dep_emp():
    for x in dep_tup:
        dep_list = []  # define list here
        for names in employees:
            if x == employees[names]["em_department"]:
                dep_list.append(employees[names])

        if dep_list:
            dep_dict[x] = dep_list

您的数据结构dep_list只是在获取雇员列表中的所有雇员。 通过编写以下行:

dep_dict[x] = dep_list

您实际上是将每个“ x”映射到对dep_list的引用,无论如何都将是相同的。 相反,您要执行的操作是将employee [names]附加到存储在每个dep_dict [x]处的独立列表中。 如果密钥尚未存储在dep_dict中,则可以通过初始化列表,或者如果该密钥已经存在,则通过将雇员[名称]串联起来来实现。

def dep_emp():
    for x in dep_tup:
        for names in employees:
            if x == employees[names]["em_department"]:
                dep_dict[x] = dep_dict.get(x, []) + employees[names]
                continue

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM