John Machin wrote: > Ben wrote: > >>Hello... >> >>I have set up a dictionary into whose values I am putting a list. I >>loop around and around filling my list each time with new values, then >>dumping this list into the dictionary. Or so I thought... >> >>It would appear that what I am dumping into the dictionary value is >>only a pointer to the original list, so after all my iterations all I >>have is a dictionary whose every value is equal to that of the list the >>final time I looped around :-( >> >>Is there a way to acheive what I was attempting ? I have done something >>almost identical with classes in a list before, and in that case a new >>instance was created for each list entry... >> >> >>I hope this makes some sense, and doesn't seem to head bangingly >>simple... >> > > > Do you consult your physician over a video link while wearing a ninja > costume down an unlit coal mine at midnight? > > Please consider the possibility that your description of what you think > your code might be doing is not enough for diagnosis. > > You may need to supply: > (1) a listing of your code > (2) a small amount of input data > e.g. [(1, 'foo'), (42, 'bar'), (1, 'zot')] > (3) the output you expect from that input: > e.g. {1: ['foo', 'zot'], 42: ['bar']} > One of the fascinating things about c.l.py is that sometimes a questin will be posted that makes almost no sense to me, and somebody else will casually read the OP's mind, home in on the issue and provide a useful and relevant answer.
In this case it seems transparent to me, though probably not to you, that Ben's problem is rootd in the following behaviour, well-known in python but frequently confusing to noobs: >>> a = [1, 2, 3] >>> firstlist = a >>> a.append('another element') >>> firstlist [1, 2, 3, 'another element'] >>> Ben probably needs to look at creating copies using the list() type: >>> a = [1, 2, 3] >>> firstlist = list(a) >>> a.append('another element') >>> firstlist [1, 2, 3] >>> or perhaps, in omore complex circumstances, using the copy module. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list