Numpy problem: Arrays in a list of dictionaries
Robert Kern
robert.kern at gmail.com
Tue Apr 17 15:36:41 EDT 2007
ZMY wrote:
> I am new to Numpy/Pylab, and I am trying to construct a list of
> dictionaries with arrays as the items, for example:
>
>>>> dict = {1: array([2, 3, 4]), 2: ''}
>>>> list1 = []
>>>> for i in range(3): list1.append(dict.copy())
> ...
>>>> list1
> [{1: array([2, 3, 4]), 2: ''}, {1: array([2, 3, 4]), 2: ''}, {1:
> array([2, 3, 4]), 2: ''}]
>>>> list1[0][1][1]=100
>>>> list1
> [{1: array([ 2, 100, 4]), 2: ''}, {1: array([ 2, 100, 4]), 2:
> ''}, {1: array([ 2, 100, 4]), 2: ''}]
>
>>>> list1[0][2]='Jack'
>>>> list1
> [{1: array([ 2, 100, 4]), 2: 'Jack'}, {1: array([ 2, 100, 4]),
> 2: ''}, {1: array([ 2, 100, 4]), 2: ''}]
>
> So the strings can be assigned seperately but arrays can not. What is
> the problem here?
When you call dict.copy(), all it does is make a copy of the dictionary; each
copy of the dictionary still refers to the same objects.
list1[i][1] refers to the same array for all i, so when you modify it in-place
like you did, you will see the modifications in every reference to that object.
list[i][2] also referred to the same string for all i until you *replaced* the
entry in the 0'th dictionary.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list