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

Charlie Clark charlie@begeistert.org
Fri Apr 11 04:40:02 2003


Hi Chris,

please set your mailer to send plain text. It would be so nice if Mailman 
either refused HTML-mail or just threw the HTML out then we wouldn't get 
this and the associated junk all the time (in this case well over fifty 
lines) :-(

> This is a multi-part message in MIME format.
> 
> ------=_NextPart_000_0001_01C2FFB9.773F8780
> Content-Type: text/plain;
>     charset="us-ascii"
> Content-Transfer-Encoding: 7bit


> Here is a snippet of my code:
>  
> <snippet>
> # line item = [transactions (dict), associations (list), goal (int)] 
> line_item = [{'Date': ()}, [], 0]
>  
> # budget = {dictionary of line_items}
> grossinc = {}
>  
> #define budget line items
> grossinc['salary'] = line_item
> grossinc['interest'] = line_item
> grossinc['dividends'] = line_item
> grossinc['other'] = line_item
>  
> grossinc['salary'][goal] = 3333
> grossinc['other'][goal] = 575
> </snippet>
>  
> results in :
>  
> >>> grossinc
> {'salary': [{'Date': ()}, [], 575], 'dividends': [{'Date': ()}, [],
> 575], 'other': [{'Date': ()}, [], 575], 'interest': [{'Date': ()}, [],
> 575]}
>  
> It assigned 575 to all of them! I want to it to be:
>  
> {'salary': [{'Date': ()}, [], 3333], 'dividends': [{'Date': ()}, [], 0], 
> 'other': [{'Date': ()}, [], 0], 'interest': [{'Date': ()}, [], 575]}
>  
> Can anyone point me in the right direction? I can't seem to make sense of 
> this.

What are you trying to do exactly? The problem seems to stem from the 
subtle difference between references and copies. I cannot understand why 
you are assigning the whole line item to different parts of a dictionary 
but by doing this grossinc['salary'] is the a reference to the same object 
as grossinc['other'], ie. line_item and so you're just overwriting line_item
However, I can't actually see this working with line_item[goal] or even 
line_item['goal'] as I don't see "goal" being initialised anywhere in order 
to slice the list and it's you can't use it as a key in a list.

Could you please provide a more detailed description of what you want to 
do. I think the first step to the solution will be to model the data 
correctly.

Charlie