Dictionary problem

Duncan Booth duncan at NOSPAMrcp.co.uk
Mon Nov 17 18:13:35 CET 2003


"Elena Schulz" <elena.schulz at gmx.net> wrote in 
news:mailman.799.1069086944.702.python-list at python.org:

> I've the following code:
> 
> 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}]
> 
> thanx for any hint how to achieve that

Well, firstly I would say that you don't have the code you posted, because 
if you did you would be getting:

    NameError: name 'myDict' is not defined

Anyway, if you want your list to contain three different dictionaries 
instead of three references to the same dictionary, then you have to create 
a new dictionary each time. This should do for your example:

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

Remember that Python never, ever, makes a copy of an object unless you 
explicitly tell it to make a copy. Usually all it does is shuffle around 
references to the same objects.

If you had a load of other values in your dictionary, and wanted to have 
different dictionaries with just the id field different, you could do 
something like:

myDict = { 'a': 1, 'b': 2 }
myList = []
for i in range(3):
    myDict['id'] = i
    myList.append(myDict.copy())


-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list