[Tutor] assignment to 1 item in dict assigns to all items in dict?

Sean 'Shaleh' Perry shalehperry@attbi.com
Fri Apr 11 00:58:01 2003


Chris is confused about why a seemingly simple assignment ends up changing all 
of the elements in his dictionary.

On Thursday 10 April 2003 21:32, Chris Somerlot wrote:
>
> #define budget line items
> grossinc['salary'] = line_item
> grossinc['interest'] = line_item
> grossinc['dividends'] = line_item
> grossinc['other'] = line_item
>

here is your problem.  Each one of these assignments is *NOT* a copy but just 
a reference.  So all of your dictionary entries are just references to the 
same variable.

>>> a = myList
>>> b = myList
>>> a
[1, 2, 3, 4, 5, 6]
>>> b
[1, 2, 3, 4, 5, 6]
>>> a[2] = 10
>>> a
[1, 2, 10, 4, 5, 6]
>>> b
[1, 2, 10, 4, 5, 6]

You will see this referred to as a "shallow copy".  What you want is called a 
"deep copy".

>>> import copy
>>> c = copy.deepcopy(myList)
>>> c[2] = 0
>>> a
[1, 2, 10, 4, 5, 6]
>>> b
[1, 2, 10, 4, 5, 6]
>>> c
[1, 2, 0, 4, 5, 6]

Hope that helps.