How to store the reference of a dictionary element ?

Terry Reedy tjreedy at udel.edu
Thu Dec 19 22:29:13 EST 2002


"Alfredo P. Ricafort" <alpot at mylinuxsite.com> wrote in message
news:mailman.1040344046.28296.python-list at python.org...

> On Fri, 2002-12-20 at 06:38, Terry Reedy wrote:
> > If the object is mutable and is changed, then the change is
visible no
> > matter how you access it.  This is a common 'gotcha' for newbies
who
> > mistakenly think that assignment creates a copy, which it does
not.
> > To illustrate:
> >
> > >>> d={}
> > >>> d['p']=[1,2]
> > >>> d['c']=[3,4,d['p']] # equivalent to what I wrote and quoted
above
> > >>> id(d['p']), id(d['c'][2])
> > (7953824, 7953824)
> > >>> d['p'].append(5) # a change to the parent value list
> > >>> d['c'][2] # access via the child *does* see the change
> > [1, 2, 5]
> >
> > Terry J. Reedy

> Similarly, and following your example, if someone change the value
of
> d['p'] like this:
>
>   d['p']=[1,2,5]
>
> instead of this
>
>   d['p'].append(5)
>
> then d['c']'s reference to d['p'] will be lost.

This is not a 'change to the value of the parent list', which I
believe was your phrase originally, but a replacement of the parent
list by a new list.  (And d['c']'s reference is not lost, it is
unchanged.)  Doing something different produces a different effect.
Doing the wrong thing produces the wrong effect.  So what?

Yes, if you have two references to one object, and you replace one of
the two with a reference to another object while leaving the other
alone, then you now have two reference to two different objects.
Again, so what?  The only reason to make the change is if you want the
two to be different!  So why complain when an action does what it is
intended to do?  More specifically, since you can completely change
the contents of the original list , the value d['p'] (that is also
d['c'][2]), however you want, there is no need to to replace it with a
new list object except to make it different from d['c'][2] (and
similarly for other children).

I believe that if you stop fighting Python, carefully read what I and
others have written, and start experimenting with the interactive
interpreter, you should be able to produce something that works well
enough for you.

Terry J. Reedy





More information about the Python-list mailing list