Python nested dict comprehension with sets

2019-06-03 15:51发布

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条回答
我命由我不由天
2楼-- · 2019-06-03 16:40

Just reverse the order of the two loops:

j = dict((a, i) for i, s in enumerate(l) for a in s)
查看更多
登录 后发表回答