Dictionary and List

Jason Stokes jstok at bluedog.apana.org.au
Fri Oct 22 07:51:17 EDT 1999


On Fri, 22 Oct 1999 10:52:45 GMT, sorot at my-deja.com <sorot at my-deja.com> wrote:

>I'm using python 1.5.1. While i'm writing the part of python script
>like this
>
>## Part of script ##
>my_list = []
>my_dict = {'a':'','b':[]}
>x = ['a','b','c','d']
>for i in range(0,len(x)):
>   my_dict['a'] = x[i]
>   my_list.append(my_dict)
>
>print my_list
>## end ##
>
>The out put should be like
>my_list = [{'a':'a','b':[]},{'a':'b','b':[]},{'a':'c','b':[]},
>{'a':'d','b':[]}]
>
>But i got output
>my_list = [{'a':'d','b':[]},{'a':'d','b':[]},{'a':'d','b':[]},
>{'a':'d','b':[]}]

You're inserting a reference to the same object my_dict into a list, four
times.  To get four different copies you need to copy my_dict and store in
the list the reference to the new object.

-- 
Jason Stokes: jstok at bluedog.apana.org.au




More information about the Python-list mailing list