Dictionary problem
Alex Martelli
aleax at aleax.it
Mon Nov 17 12:09:17 EST 2003
<posted & mailed>
Elena Schulz wrote:
> myList = []
> for i in range(3) :
> myDict['id']=i
> myList.append(myDict)
>
> myList becomes: [{'id':2}, {'id':2}, {'id':2}] but I want: [{'id':0},
> {'id':1}, {'id':2}]
So, you don't want to append myDict itself, but, rather, a copy of it.
> thanx for any hint how to achieve that
Instead of:
myList.append(myDict)
which appends myDict itself, append a copy, e.g.:
myList.append(myDict.copy())
or
myList.append(dict(myDict))
Python doesn't make copies by default: when you want a copy, you ask
for one explicitly, as in these two examples.
> (Please answer to my mail address directly as I am currently not
> subscribed to this list, thanks)
Answering by both posting and mailing as requested.
Alex
More information about the Python-list
mailing list