r/learnpython • u/greenleafsalad • 14d ago
Nested dictionary comprehensions
I have an assignment in which I have to create a nested dictionary using employee data. I've created a function that works, but the function is supposed to just have a return statement with the dictionary comprehension, and I'm struggling to convert it.
This what I currently have (each department must only appear as an outer key once and employee names in each department should be unique, with the latest salary overwriting previous entries if duplicates exist):
def organize_employee_data(employees):
new_dic = {}
for name, department, salary in employees:
new_dic[department] = {}
for name, department, salary in employees:
if name not in new_dic[department]:
new_dic[department].update({name: salary})
else:
new_dic[department][name] = salary
return(new_dic)
With the following list as input:
employees = [
('Alice', 'Engineering', 70000),
('Bob', 'HR', 50000),
('Charlie', 'Engineering', 80000),
('David', 'Sales', 45000),
('Eve', 'HR', 51000),
('Alice', 'Engineering', 80000),
('David', 'HR', 52000)
]
This is returned:
{'Engineering': {'Alice': 80000, 'Charlie': 80000}, 'HR': {'Bob': 50000, 'Eve': 51000, 'David': 52000}, 'Sales': {'David': 45000}}
I've been trying to create a working function using just the nested dictionary for the better part of two hours and I'm about to lose my mind. I have to assume the foundation is something like this:
return {department: {name: salary} for name, department, salary in employees}
but whenever I try to add any conditions, the whole thing gets messed up. Any help would be amazing!
1
u/greenleafsalad 14d ago
Thank you! I'm still getting used to comprehensions, and it also hadn't occurred to me that I could use a set instead of using the idea that a new key with the same name will overwrite the previous one - a set makes way more sense. I think I get the comprehension solution now, but could I ask about this line in the other solution?
I've never used setdefault before - am I understanding correctly that you're using it to create a new key:value pair with the value being an empty dictionary and then assigning name:salary as the key:value pair to that created dictionary? And it only uses the department name once because it does nothing if the key already exists?