Newbie question: Dictionary of lists
Marc Christiansen
tolot at utolot.toppoint.de
Wed Feb 16 16:49:24 EST 2000
Kossmann, <BKossmann at dthr.ab.ca> wrote:
> Hello, Python gurus!
Much too much honor! I'm by far not a guru. :-)
> Trouble is, when I implement my FOR loop as below, *all* of the dictionary's
> January elements are updated to the value of the last January item in the
> history file. I've searched high and low for a solution, but I'm stumped.
[...]
> # Null list required to add an element if it's not the first element
> if not history.has_key(dictionaryKey):
> history[dictionaryKey] = nullList
This line is your problem. Since everything in python is a reference
(this bites everyone at least ones), for every dictionaryKey you put a
reference to nullList into the dictonary and hence modify nullList in
your code. Try
history[dictionaryKey] = nullList[:]
This will make a copy of nullList and put a reference to this copy in
the dictionary.
I'm sure others will explain it better.
Ciao
Marc
More information about the Python-list
mailing list