When running the following code, Python2.7 throws a NameError. This happens when the second dict, paychecks
, is evaluated. The first dict, employees
, is fine.
employees = { employee.ID:employee for employee in company.employees }
paychecks = {
paycheck.ID:paycheck for paycheck in employee.paychecks
for key, employee in employees
}
!!! NameError: global name 'employee' is not defined
Is this invalid Python or a bug in my code? And what's a better way to do it?
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:as you need to first loop over
employees
beforeemployee
is set.For list, dict and set comprehensions, picture the loops as nested
for
statements:If you were to nest the loops in the order you specified them, it should immediately be clear why you get a
NameError
onemployee
:Here the outer loop tries to access a non-existing
employee
object.