如何评估嵌套Python Dict理解中的属性

时间:2013-12-15 22:31:10

标签: python python-2.7 dictionary-comprehension

运行以下代码时,Python2.7会抛出NameError。当第二个字典paychecks被评估时会发生这种情况。第一个词典employees很好。

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

这是无效的Python还是我的代码中的错误?什么是更好的方法呢?

1 个答案:

答案 0 :(得分:4)

您需要按照嵌套顺序列出循环;你有倒退的订单。您还需要使用dict.items()方法生成两个键值。这有效:

paychecks = {paycheck.ID: paycheck
    for key, employee in employees.items()
    for paycheck in employee.paychecks}

因为您需要在设置employees之前首先遍历employee

对于list,dict和set comprehensions,将循环描绘为嵌套的for语句:

for key, employee in employees.items():
    for paycheck in employee.paychecks:
        paychecks[paycheck.ID] = paycheck

如果您按照指定的顺序嵌套循环,应立即明确为什么在NameError上获得employee

for paycheck in employee.paychecks:
    for key, employee in employees.items():
        paychecks[paycheck.ID] = paycheck

这里外部循环尝试访问不存在的employee对象。