how to copy a dictionary

Neel Krishnaswami neelk at brick.cswv.com
Tue Jan 4 21:49:14 EST 2000


Roy Smith <roy at popmail.med.nyu.edu> wrote:
> If I do:
> 
> d = {'hedgehog': 'spiney norman'}
> temp = d
> temp['scotsman'] = 'earnest potgorney'
> 
> I end up changing the original dictionary, d.  It's obvious that what's 
> going on is when I do temp = d I get a pointer to the same object 
> instead of a new object.  My question is, how do I force a new object to 
> be created, so when  modify it, I don't also modify the original?

Yup. Variable assignment in Python is always a matter of rebinding. 
Thinking of it as pasting a label on an object, and then peeling it
off and pasting it on a new object is the mental model to use. :)

Your specific problem is solved with the copy module, eg:

  >>> import copy
  >>> x = {'foo': 'bar', 'baz': 'quux'}
  >>> x
  {'foo': 'bar', 'baz': 'quux'}
  >>> y = copy.copy(x)
  >>> y
  {'foo': 'bar', 'baz': 'quux'}
  >>> y['thud'] = 'garp'
  >>> y
  {'foo': 'bar', 'thud': 'garp', 'baz': 'quux'}
  >>> x
  {'foo': 'bar', 'baz': 'quux'}

This creates a shallow copy of the object. If you want a deep 
copy, use copy.deepcopy(). 


Neel



More information about the Python-list mailing list