0

[SOLVED]Why are the loop variables for k and v used in a loop to update a dictionary still defined outside the loop?(Python)

Hi there. I bumped into a code in DataCamp when I googled stg about nested dict comprehensions, and they put the -almost- equivalent for loop for the comprehension there, too. So, given nested_dict = {'first': {'a': 1}, 'second': {'b': 2}} To turn this into a dictionary with the numbers converted to floats, they did: for (outer_k, outer_v) in nested_dict.items(): for (inner_k, inner_v) in outer_v.items(): outer_v.update({inner_k: float(inner_v)}) nested_dict.update({outer_k: outer_v}) # THIS print(nested_dict) which then outputs the desired result. Now the line I marked with "THIS" is what bewilders me. How come loop vars can exist outside the loop? I'm sorry if this is sounding stupid, I had to take a break from python for some time. Lesson learned. But still, it feels as though this is something new to me. Is this due to update()? Thank you. https://code.sololearn.com/crDb301kPSS6/?ref=app

15th Nov 2022, 8:45 PM
Korkunç el Gato
Korkunç el Gato - avatar
4 Respostas
+ 6
Hi, Korkunç el Gato ! When it comes to variables, you just follow the LEGB-rules. If you try to reach a variable in the same name space, you will reach it - otherwise not. LEGB is an acronym LEGB for Local, Enclosing, Global, and Builtin scopes. A function is an encloser, a loop or a dictionary is not. Variables in comprenhsion becomes a special case, and so does variables in exceptions. So iteration variables whitin comprehentions becomes local, and can’t be reach outside the comprehension (in Python 3.x). So for example, you can reach built-ins (B) everywhere, but not local (L) variables.
15th Nov 2022, 11:04 PM
Per Bratthammar
Per Bratthammar - avatar
+ 2
Thanks a bunch, Per B.
15th Nov 2022, 11:24 PM
Korkunç el Gato
Korkunç el Gato - avatar
+ 1
By the way, this line is not needed here 😉
15th Nov 2022, 11:34 PM
Solo
Solo - avatar
+ 1
Solo Because dicts are mutable, right, it's updated inside anyway. Yeah actually that was some other question that was boggling me but I forgot to ask about it. So I hit jackpot here now, thanks 😊 The comprehension they did is different than their own loop btw(So I didn't include it in my q). A bit of lack of care there on their part.
15th Nov 2022, 11:48 PM
Korkunç el Gato
Korkunç el Gato - avatar