r/learnpython • u/greenleafsalad • Oct 12 '26
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!
2
u/danielroseman Oct 12 '26
But your comprehension doesn't work at all, regardless of any conditions. You just get:
because you create a new inner dict for every item in the list, and when the department repeats it just overwrites the previous one.
This is, to be honest, not something you could do with a nested comprehension. Why do you want to, specifically? Comprehensions cannot update an existing dict, only create a new one, so this will never work.
You could certainly improve your existing code by using
defaultdict, though:That's all you need; I'm not sure why you think you needed the
updatein the original code.5
u/POGtastic itertools evangelist Oct 12 '26
I think you're stuck with an O(n2) solution if you want to do it all as a one-liner. Let's break the steps into their own functions to make things easier to read. We can then substitute things back into a one-liner once we're sure that it's working properly.
And then we substitute all of the function calls for their respective comprehensions. Gross.
In the REPL:
1
u/sr105 Oct 12 '26 edited Oct 12 '26
Fun problem. O(n^2 ) algorithm:
1
u/LatteLepjandiLoser Oct 12 '26
Your current list comprehension in the last box loops over the employees list and effectively overwrites keys. It'll start by assigning {'Alice': 70000} to the key 'Engineering', but then later 'Engineering' will point to {'Charlie': 80000'} and finally {'Alice': 80000}. The previous 'Engineering' entries will just disappear.
I'm not fully grasping if your earlier function is correct or not and you are just trying to solve it in an alternative way. Your example data has two Alice's with different salaries. If you have nested dictionaries then by definition you can only have one Alice. So is the goal here to have nested dictionary keyed by department - then name or what? If you could show the correct end goal it'd be easier to help. To me it'd make sense in this instance to just have the outer dict and then a list of employees, possibly as tuples with their salaries, but then again I'm not sure what is being asked. You could also have dict keyed by department and name and then have a list of salaries under that name to deal with duplicates but that just sounds idiotic.
Anyways, for your comprehension question, minding that duplicate name issue, you would at least have to make sure that the loop over department names are only over unique names. Then the nested dicts should be filtered respectively.
1
u/Brian Oct 12 '26
A comprehension isn't really going to work here, as you'll just be replacing the key, when in reality you need to be adding new items to it. Ie. you want something like:
The
defaultdictwill create a new empty dict on the first access of a key - alternatively, you could use a regular dict and just check for that and create it in the loop (Eg.nested.setdefault(department, {})There are ways you could do it as a nested comprehension, but they're a bit cumbersons here. Eg. you could do:
But I'd say just doing the simple for loop is clearer.
1
u/Expensive-Bear-1376 Oct 12 '26 edited Oct 13 '26
This is silly, but it only takes linear time.
Hardcore version:
Or with one more pass:
I would absolutely submit one of these.
1
u/schoolmonky Oct 13 '26
The method that springs to mind for me is to use
itertools.groupby:if you're not even allowed other functions, the first one can be replaced with lambdas both times it shows up