Python nested dict comprehension with sets

2019-06-03 16:08发布

问题:

Can someone explain how to do nested dict comprehensions?

>> l = [set([1, 2, 3]), set([4, 5, 6])]
>> j = dict((a, i) for a in s for i, s in enumerate(l))
>> NameError: name 's' is not defined

I would have liked:

>> j
>> {1:0, 2:0, 3:0, 4: 1, 5: 1, 6: 1}

I just asked a previous question about a simpler dict comprehension where the parentheses in the generator function were reduced. How come the s in the leftmost comprehension is not recognized?

回答1:

Just reverse the order of the two loops:

j = dict((a, i) for i, s in enumerate(l) for a in s)