how to copy a dictionary

Tim Peters tim_one at email.msn.com
Tue Jan 4 21:52:22 EST 2000


[Roy Smith]
> 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?

For dicts in particular,

    temp = d.copy()

makes a shallow copy.  For the general case, see copy.copy() and
copy.deepcopy() in the std library.

Note that

    copy() (dictionary method)

is the first "copy" entry in the Library Ref's index.

that's-a-hint<wink>-ly y'rs  - tim






More information about the Python-list mailing list