Newbie question: Dictionary of lists
Remco Gerlich
scarblac-spamtrap at pino.selwerd.nl
Wed Feb 16 12:12:00 EST 2000
Kossmann, Bill wrote in comp.lang.python:
> 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.
This is a problem with references. Remember that *everything* is a reference
in Python.
> # TEST.PY ============================================================
>
> import string
>
> history = {}
> history['DEFAULT'] = [31,29,31,30,31,30,31,31,30,31,30,31]
>
> # Null elements - one for each month of the year (Jan ... Dec)
> nullList = ['', '', '', '', '', '', '', '', '', '', '', '']
>
> # Short test file (16000 lines in production)
> histFile = open("2000.txt", "r")
> for histLine in histFile.readlines():
> histRcd = string.split(histLine, ",")
>
> # Key is our cost centre code
> dictionaryKey = histRcd[0]+histRcd[1]+histRcd[2]+histRcd[3]
>
> # Null list required to add an element if it's not the first element
> if not history.has_key(dictionaryKey):
> history[dictionaryKey] = nullList
Note: history[dictionaryKey] now points to the same list as nullList.
Every key you do this for, history[key] points to that same list.
> # Obviously must evaluate for other months, but January will do for testing
> if (histRcd[4][:3] == 'JAN'):
> history[dictionaryKey][0] = float(string.strip(histRcd[5]))
And now you change that list. So now nullList is changed,
history[dictionaryKey] is changed, everywhere you point to that list, it's
changed. They're all just different names for the same list.
[snip rest]
Try initializing it with
history[dictionaryKey] = nullList[:]
The [:] makes a slice that's equal to the whole list - except that it's
a *copy* of the list. That way, all the lists are seperate.
--
Remco Gerlich, scarblac at pino.selwerd.nl
6:07pm up 85 days, 11 min, 6 users, load average: 0.08, 0.02, 0.01
More information about the Python-list
mailing list