dictionary.copy()?

Alex Martelli aleax at mac.com
Wed Mar 21 06:53:04 CET 2007


7stud <bbxx789_05ss at yahoo.com> wrote:

> Here is some example code:
> 
> d = {"a":"hello", "b":[1, 2, 3]}
> 
> x = d.copy()
> d["b"][0]=10
> print x
> 
> output:
> {'a': 'hello', 'b': [10, 2, 3]}
> 
> It looks like the key names of a dictionary store pointers to the
> values?  Or does a dictionary object manage pointers to keys and
> values, so copy() above just copies 4 pointers?

dict objects hold references (roughly the same as C pointers) to keys
and values, and dict.copy does a shallow copy.  If you want a deep copy,
import copy and x=copy.deepcopy(d) instead.

Deep copies are very costly (because they copy a lot of data bits rather
than just references), so it's quite sensible to have to ask for one
very specifically in the rare cases in which you really want it.


Alex
 



More information about the Python-list mailing list