[Tutor] Re: Self referencing within a dictionary

John Fouhy jfouhy at paradise.net.nz
Sat Apr 2 23:53:56 CEST 2005


Andrei wrote:
> Liam Clarke wrote on Sat, 2 Apr 2005 22:12:49 +1200:
>>I know that as above doesn't work, but was just wondering if it's
>>possible, and if it's a Bad Thing?
> Max has already shown it's possible. Whether it's a Bad Thing... I don't
> see why it would be. But I also can't imagine right now any realistic cases
> where it would be useful to have a dictionary contain itself as a value.

It wouldn't contain itself as a value.

This is basically what Liam said:

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

In this case, the second line creates a _new_ dictionary, which maps 'c' 
to whatever the previous dictionary mapped 'a' to.  The original 
dictionary is discarded.  The result looks like this:

 >>> foo
{'a': 1, 'c': 1, 'b': 2}

And it is absolutely the same as you would get if you just did:
 >>> foo = { 'a': 1, 'c': 1, 'b': 2 }

I don't think anyone would call that a Bad Thing..

You could also do this:

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

Now we're not creating a new dictionary.  But the code still says: "Look 
up the value associated with 'a' in foo, and then associate that value 
with 'c' in foo".  And the end result is the same:

 >>> foo
{'a': 1, 'c': 1, 'b': 2}

Of course, if foo['a'] were mutable, it could cause problems.

 >>> foo = {'a':[]}
 >>> foo['b'] = foo['a']
 >>> foo
{'a': [], 'b': []}
 >>> foo['a'].append(3)
 >>> foo
{'a': [3], 'b': [3]}

But again, there are other ways of achieving this.  (eg, x = []; foo = 
{'a':x, 'b':x})  And maybe it's even what you wanted.

You could even make foo contain itself as a value.

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

Whether this is useful, I'm not sure... But there's no magic and it's 
not breaking any rules.

To answer what maybe the original question meant to be --- "Can I make 
it so that foo['c'] is the _same_ as foo['a'], and if I reassign to 
foo['a'], this will also change foo['c']" --- I don't think so.  Not 
with the unmodified builtin dictionary.

HTH.

-- 
John.


More information about the Tutor mailing list