2

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}]
Juergen
  • 12,378
  • 7
  • 39
  • 55
  • whats the intention of doing [{}]*2, since dicts are mutable ,you are creating a reference of same dict twice, so whatever changes you make to first dict will be reflected in the second... – labheshr Oct 23 '15 at 23:05
  • Unless, I'm missing something, what about an simple assignment? `data[1] = {3: 4}` In [33]: data Out[33]: [{}, {3: 4}]` – flamenco Oct 23 '15 at 23:21

3 Answers3

2

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'}, {}]
Chad S.
  • 6,252
  • 15
  • 25
  • I edited your answer to exemplify , via `id()` function, the fact the `[{}] * 2` points to the same object. Hope you are ok with it! – flamenco Oct 23 '15 at 23:55
0

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.

Juergen
  • 12,378
  • 7
  • 39
  • 55
0

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.

Anthony Pham
  • 3,096
  • 5
  • 29
  • 38