[Tutor] Self referencing within a dictionary

Max Noel maxnoel_fr at yahoo.fr
Sat Apr 2 12:38:05 CEST 2005

On Apr 2, 2005, at 12:12, Liam Clarke wrote:

> Hi,
> Out of curiosity, is it possible to create a dictionary like this -
> foo = {'a':1, 'b':2, 'c':foo['a']}
> I know that as above doesn't work, but was just wondering if it's
> possible, and if it's a
> Bad Thing?
> Regards,
> Liam Clarke

	It doesn't work because the expression {'a':1, 'b':2, 'c':foo['a']} is 
evaluated before the assignment. It has to be, as Python doesn't do 
this kind of lazy evaluation. But when the expression is evaluated, foo 
doesn't exist yet, as the assignment hasn't happened yet. Therefore it 
	If foo existed before that line, it would work. Witness the following 

 >>> foo = {'a':555, 'b':1}
 >>> foo
{'a': 555, 'b': 1}
 >>> foo = {'a':1, 'b':2, 'c':foo['a']}
 >>> foo
{'a': 1, 'c': 555, 'b': 2}

	You'd have to have a good reason to do that, though.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

More information about the Tutor mailing list