building lists of dictionaries

Ernesto García García titogarcia_nospamplease_ at gmail.com
Sun Jul 23 16:56:58 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]
> 
> Tried both Python 2.4.1 and 2.5 beta, Linux, GCC 4.0.2

Of course. The expression within the list comprehension is evaluated for 
each iteration, so that the objects are recreated each time. The copy() 
for the dictionary is also not needed:

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

Ernesto



More information about the Python-list mailing list