building lists of dictionaries

Tim Chase python.list at tim.thechases.com
Sun Jul 23 17:15:23 EDT 2006


>>parinfo = [{'value':0., 'fixed':0, 'limited':[0,0],
>>'limits':[0.,0.]}.copy() for i in xrange(0,6)]
>>
>>However, this will still reference internal lists that have
>>been referenced multiple times, such that
>>
>> >>> parinfo[5]['limited']
>>[0, 0]
>> >>> parinfo[4]['limited'][0] = 2
>> >>> parinfo[5]['limited']
>>[2, 0]
> 
> Interesting. Cut-and-paste to my python prompt and I get
> 
>>>>parinfo[5]['limited']
> 
> [0, 0]

Hmm...same behavior on my 2.3.5 here.  Looks like the problem lay 
within the for-loop version I tried first:

parinfo = [{'value':0., 'fixed':0, 'limited':[0,0],
'limits':[0.,0.]}]
for i in xrange(1,6): parinfo.append(parinfo[0].copy())

which copied the elements, but when the elements were references 
to other lists, only the references were copied.  I just tried it 
with the second method I suggested (the list-comprehension one 
you reference here) and it doesn't have the same problem as the 
crazy for-loop, and as shown by others, doesn't need the 
superflous copy() call either.

That'll teach me to test both proposed ideas, rather than making 
assumptions.

-tkc









More information about the Python-list mailing list