Dictionary problem

Batista, Facundo FBatista at uniFON.com.ar
Mon Nov 17 12:01:29 EST 2003


#- myList = []
#- for i in range(3) :
#-     myDict['id']=i
#-     myList.append(myDict)

The problem here is you're binding the same dictionary to each element in
the list. So, when the dictionary changes, change all the elements.



#- myList becomes: [{'id':2}, {'id':2}, {'id':2}] but I want: [{'id':0},
#- {'id':1}, {'id':2}]
#- 
#- thanx for any hint how to achieve that

You need to store a copy of the dictionary:

>>> myList = []
>>> myDict = {}
>>> for i in range(3):
	myDict['id'] = i
	myList.append(myDict.copy())

>>> myList
[{'id': 0}, {'id': 1}, {'id': 2}]

.	Facundo





. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
ADVERTENCIA  

La información contenida en este mensaje y cualquier archivo anexo al mismo,
son para uso exclusivo del destinatario y pueden contener información
confidencial o propietaria, cuya divulgación es sancionada por la ley. 

Si Ud. No es uno de los destinatarios consignados o la persona responsable
de hacer llegar este mensaje a los destinatarios consignados, no está
autorizado a divulgar, copiar, distribuir o retener información (o parte de
ella) contenida en este mensaje. Por favor notifíquenos respondiendo al
remitente, borre el mensaje original y borre las copias (impresas o grabadas
en cualquier medio magnético) que pueda haber realizado del mismo. 

Todas las opiniones contenidas en este mail son propias del autor del
mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones
Personales S.A. o alguna empresa asociada. 

Los mensajes electrónicos pueden ser alterados, motivo por el cual
Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación
cualquiera sea el resultante de este mensaje. 

Muchas Gracias.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20031117/f88fe6da/attachment.html>


More information about the Python-list mailing list