[Tutor] list of dict question

Francesco Loffredo fal at libero.it
Sun Oct 10 20:21:28 CEST 2010

On 09/10/2010 10.25, Alan Gauld wrote:
> "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 well.
> You need to get two boxes!
I obviously haven't been clear in my question, sure I know that if you 
change one object you lose the previous contents, but (hope this makes 
my question clear) why should the append method of the list store a 
pointer to the dictionary, rather then a copy of that dictionary? If it 
did, Roelof's code would work perfectly, and you could store in a list 
all the subsequent changes of a dictionary without calling them with 
different names. For example (and this should make my previous example a 
bit fuller), if you had a dictionary containing the current status of a 
system, and you wanted to keep an history of that status (well, I'd use 
a file, but let's imagine you had to use a list), you could simply add 
the (newer version of the) dictionary to the list:

>> myDictList.append(UpdateIt(myDict))

This would be much more elegant and readable than creating a different 
dictionary (meaning a different name) for every state of the said 
system, and making sure you never repeat a name twice, or you'll lose 
the state you saved some time ago...
I understand that if .append() stored a copy of the dict in the list, 
you will end up with lots of copies and a huge amount of memory used by 
your list, but that's exactly what will happen if you make those copies 
yourself. But you wouldn't have to devise a way to generate a new name 
for the dictionary every time you need to update it.

Thank you for your help
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.862 / Database dei virus: 271.1.1/3186 -  Data di rilascio: 10/09/10 08:34:00

More information about the Tutor mailing list