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

Chris Somerlot cdsomerl@murray-ky.net
Fri Apr 11 09:03:01 2003


> 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

I see that you're right, I want to create a new instance of line_item
each time and add it into the dictionary grossinc instead of making a
reference, but I'm still confused about a good way to do that. Make a
class? My code should have read:

# line item = [list of 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'][2] = 3333
grossinc['other'][2] = 575