[Tutor] list of dict question

Alan Gauld alan.gauld at btinternet.com
Sat Oct 9 10:25:21 CEST 2010

"Francesco Loffredo" <fal at libero.it> wrote

> > On the next iteration you overwrite those two dictionaries
> > with new values then append them to the list again.
> > So you wind up with 2 copies of the updated dictionaries.
> > ...
> This is difficult for me too: why does this happen? Or, more 
> correctly,
> why should this happen?

It happens because you can't store two objects in one.
There is only one dictionary. If you change its value you
change its value.

> How can you save the current contents of a dictionary in a list,
> making sure that the saved values won't change if you update the 
> dict?

You need to save a copy of the dictionary. ie Create a new dictionary.
If you put a box of white eggs in your shopping basket you cannot put
brown eggs into that box and expect to still have the white ones as 
You need to get two boxes!

> You tell Roelof that the dictionary must be created at every loop, 
> but
> if so, where goes the elegance of
> myDictList.append(UpdateIt(myDict))

I don't understand what you mean here. What elegance?
Can you give a slightly fuller example?

You can update an existing dictionary in a list, but it doesn't 
the original vesion any more than replacing white eggs with brown
preserves the white ones.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list