You have a mix order for your loops; they are considered nested from left to right, so for r in a[g] is the outer loop and executed first. Swap loops:
print [r['n'] for g in good for r in a[g]]
Now g defined for the next for r in a[g] loop, and the expression no longer throws an exception:
>>> a={ ... 1: [{'n': 1}, {'n': 2}], ... 2: [{'n': 3}, {'n': 4}], ... 3: [{'n': 5}], ... } >>> good = [1,2] >>> [r['n'] for g in good for r in a[g]] [1, 2, 3, 4]
source share