Вопрос

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:

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top