简体   繁体   中英

Python dictionaries with loops

I'm trying to output a dictionary with department titles as keys and a list of dictionaries with only the employees within that department as its corresponding value. I'm close, but when I run this function, dep_dict attaches ALL department employees to each key. This is what it's doing:

{
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

But instead it should look like this (if there are 2 departments) and assuming employee A works for department1 and employee B works for department2:

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

Note: dep_tup is a tuple of all department names input by user, employees is a dictionary consisting of all employees and their information (key = employee name)

You can avoid dep_dict[x] = dep_list for every name in employees .

You have to reset/redefine dep_list for each department:

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

Your data structure, dep_list, is simply acquiring all the employees within your employees list. By writing the line:

dep_dict[x] = dep_list

you are essentially mapping every 'x' to a reference to dep_list, which will be the same no matter what. What you want to be doing instead is appending employees[names] into independent lists stored at each dep_dict[x]. This can be accomplished by initializing a list if the key is not already stored in dep_dict or concatenating employees[names] that key if it already exists.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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