[Tutor] Inserting one dictionary into another
Kent Johnson
kent37 at tds.net
Thu Jan 1 20:14:20 CET 2009
On Thu, Jan 1, 2009 at 11:04 AM, Keith Reed <keith_reed at fastmail.net> wrote:
> I'm having trouble assigning a dictionary as a value within another:
>
>
> -------- Code Snippet Start --------
>
> for line in fromchild.readlines():
> itemarray = line.strip().split(":")
> parentdictkey = itemarray[0]
> print 'parentdictkey = ' + parentdictkey
> for index in range(len(headerinfo)):
> nesteddict[headerinfo[index]] = itemarray[index]
> #print nesteddict
> parentdict[parentdictkey] = nesteddict
> nesteddict.clear()
> print
> '-------------------------------------------------------------------------\n'
> print parentdict
The problem is that you are re-using the same dict rather than
creating a new one each time through the loop. Every value of
parentdict is the same; when you clear nesteddict you are clearing the
one shared dict.
Python assignment copies references, not values. If you don't
understand this, read this:
http://personalpages.tds.net/~kent37/kk/00012.html
The solution is easy; just make a new dict at the start of the loop:
nesteddict = {}
and get rid of the clear().
Kent
More information about the Tutor
mailing list