Python scoping in dict comprehension
Asked Answered
V

1

12
>>> x = 'foo'
>>> {0: locals().get('x')}
{0: 'foo'}
>>> {0: locals().get('x' + spam) for spam in ['']}
{0: None}

What is the reason for this discrepancy in behaviour?

Variance answered 29/10, 2012 at 6:45 Comment(0)
M
16

Dict comprehensions and generator comprehensions create their own local scope. List comprehensions do not in Python 2.x, but do in Python 3. (Note that your first example is not a dict comprehension. It's just a literal dict that happens to have an expression as the value for the key 0.)

Monostome answered 29/10, 2012 at 6:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.