I defined a simple Class and generated a dict from another one:
class TestClass1:
d1 = {1:'11', 2:'22' , 3:'33'}
d2 = {d1[i]:i for i in sorted(d1, reverse=True)}
and I got:
Traceback (most recent call last):
File "C:\probe.py", line 1, in <module>
class TestClass1:
File "C:\probe.py", line 3, in TestClass1
d2 = {d1[i]:i for i in sorted(d1, reverse=True)}
File "C:\probe.py", line 3, in <dictcomp>
d2 = {d1[i]:i for i in sorted(d1, reverse=True)}
NameError: name 'd1' is not defined
I added the second class to check if the second reference to the dictionary is okay, and it is okay:
class TestClass2:
d1 = {1:'11', 2:'22' , 3:'33'}
d2 = {i:i for i in sorted(d1, reverse=True)}
Curiously, there is NO the error in TestClass2.
Please, pay attention that the NameError occurs on d1[i]
reference but does not on sorted(d1, reverse=True)
which is in the same dictionary generator scope.
This is a similar question. However, I can not approve the explanation. The problem source could not be a different scope as the scope could not be different inside {}
of the dictionary generator. It clearly shown in TestClass2
example where I remove the d1[i]
reference but use d1
in sorted(d1, reversal=True)
. Both references are inside {}
of the same dict generator.
How could it be explained?