You need to list your loops in the same order you'd nest them; you have the order backwards. You also need to use the dict.items()
method to yield both keys and values. This works:
paychecks = {paycheck.ID: paycheck
for key, employee in employees.items()
for paycheck in employee.paychecks}
as you need to first loop over employees
before employee
is set.
For list, dict and set comprehensions, picture the loops as nested for
statements:
for key, employee in employees.items():
for paycheck in employee.paychecks:
paychecks[paycheck.ID] = paycheck
If you were to nest the loops in the order you specified them, it should immediately be clear why you get a NameError
on employee
:
for paycheck in employee.paychecks:
for key, employee in employees.items():
paychecks[paycheck.ID] = paycheck
Here the outer loop tries to access a non-existing employee
object.