Question is in title. I can't make it work:
>>> data = [{}] * 2
>>> data[1].update({3:4})
>>> data
[{3: 4}, {3: 4}]
key-value pair adds to all elements of array. I expected to receive that:
[{}, {3: 4}]
Question is in title. I can't make it work:
>>> data = [{}] * 2
>>> data[1].update({3:4})
>>> data
[{3: 4}, {3: 4}]
key-value pair adds to all elements of array. I expected to receive that:
[{}, {3: 4}]
The problem is that
data = [{}] * 2
Creates a list that has the same dictionary in it twice.
To illustrate this, let's look at id(data[0])
and id(data[1])
:
>>> data = [{}] * 2
>>> data
[{}, {}]
>>> id(data[0])
4490760552
>>> id(data[1])
4490760552
Note that id(data[0]) and id(data[1]) are the same because both entries in the list refer to the same object
What you probably want is
>>> d2 = [{} for i in range(2)]
>>> d2[0][4] = 'a'
>>> d2
[{4: 'a'}, {}]
The problem is, that you added the same dictionary twice to your list.
The trouble is already in your first statement:
data = [{}] * 2
This creates a list with two times the same entry. When you update one of those, the update will be visible in both entries of the list.
Try this:
data = [ {} for i in range(2) ]
When you now do your update, you will get your expected result.
Instead of using:
data = [{}] * 2
data[1].update({3:4})
print data
which adds the same dictionary to your list, use this instead:
data = [{}, {}]
data[1].update({3:4})
print data
data[1]
now means the second {}
in your list. The result of this program is:
[{}, {3: 4}]
Why doesn't data = [{}] * 2
work? Because it you are making the same thing twice, which means you are forced to replace both {}
with {3:4}
which gives you the result you had. With data = [{}, {}]
, you can only change the second dictionary since data[0]
is the first one and data[1]
is the next item and so on.