Can't create list of dictionaries

John Machin sjmachin at
Fri Apr 10 13:53:44 CEST 2009

On Apr 10, 9:36 pm, sophie_newbie <paulgeele... at> wrote:
> Hi there,
> I've got a function that returns a dictionary, I need to loop and
> return 1000 dictionaries and append them to a list, but the thing is
> that when I do the list.append(funtThatReturnsDict()) the resulting
> only ever has 1 dictionary attached to it, even after running the
> append function 1000 times!

Do you mean that the length of the list is 1, or do you mean that the
same dictionary has been appended 1000 times?
> I've tried using dict.copy() on the dictionary that was returned from
> the function but this didn't work either.
> And the function is definately returning different dictionaries each
> time as I can see that when I print them.
> I know this is something to do with the dictionries being stored as
> references but I've no idea how to fix it seeing as the copy()
> function didn't work.

I think you had better show us your code, and the output from (say) 3
iterations (not 1000!!). If you are really doing "list.append
(functThatReturnsDict())" all in one line, break it up into multiple
lines so that some print statements can be used for debugging:

adict = functThatReturnsDict()
print "A", id(adict), len(adict), adict
print "B", len(alist), id(alist[-1])

Clean it up a bit ... the dict.copy() is extremely unlikely to be part
of a principled solution, so remove any trace of that.


More information about the Python-list mailing list