3

Imagine this object:

my_obj = {
    'Episodes' : [
        {'Tags' : ['one','two','three']},
        {'Tags' : ['three','four','five']}
            ]
        }

I want to create a set of the tags:

tags = set(tag for tag in e['Tags'] for e in my_obj['Episodes'])

However, it doesn't work because e is not defined. How can I do it??

MFB
  • 19,017
  • 27
  • 72
  • 118
  • 1
    Look at [this other question](http://stackoverflow.com/questions/3766711/python-advanced-nested-list-comprehension-syntax), which also deals with nested list comprehension syntax – inspectorG4dget Oct 05 '12 at 04:49
  • 1
    That other question is about 50 times longer and more complex than my question. If I was looking for an answer to this question, I know which one I'd rather digest. No disrespect! – MFB Oct 05 '12 at 04:56

2 Answers2

6
tags = set(tag  for e in my_obj['Episodes'] for tag in e['Tags'])

you need to change the order and get e first... :)

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
4

The trick I use to avoid getting confused by these nested comprehensions is to expand the loop in the order it appears in the comprehension.

So in your example, you have a genex:

tag for tag in e['Tags'] for e in my_obj['Episodes']

Which you can mentally expand into double loop like this:

for tag in e['Tags']:
  for e in my_obj['Episodes']:
    yield tag

And now with this structure you can quite clearly see where your error lies, with e being undefined, and see that it should really be:

for e in my_obj['Episodes']:
  for tag in e['Tags']:
    yield tag 

Which collapses back into the nested comprehension

tag for e in my_obj['Episodes'] for tag in e['Tags']

As you have already seen from the previous answers. Hope this helps!

wim
  • 338,267
  • 99
  • 616
  • 750