-1

I am witnessing a very weird behviour with the following Python code snippet.

list_of_dict = [{}]*2                  # create a list of 2 dict
list_of_dict[0]["add_to_dict_0"] = 1   # add a (key,val) pair to 1st dict

print list_of_dict[0]
print list_of_dict[1]

The output is:

{'add_to_dict_0': 1}

{'add_to_dict_0': 1}

Both the dictionaries got updated, although I (explicitly) updated only one. However, changing the initialization in Line 1 to the following:

list_of_dict = [dict() for _ in xrange(0,2)]

fixes the issue.

What is the reason for this behaviour? I am guessing that this is an artefact of the concept of name-object binding in Python (as opposed to variable-memory location binding in other languages like C/C++). My guess is that in the first case, both list_of_dict[0] and list_of_dict[1] are bound to the same dictionary object.

Is my suspicion correct? If yes, then why is the behaviour not replicated in the second case? What is the difference between dict_object = dict() and dict_object = {}?

Community
  • 1
  • 1
Shobhit
  • 773
  • 7
  • 20
  • 3
    Both `list_of_dict = [dict() for _ in xrange(0,2)]` and `list_of_dict = [{} for _ in xrange(0,2)]` work. Your question isn't actually about `dict()` vs `{}`. – vaultah Feb 23 '16 at 06:20

2 Answers2

3

There is no difference between dict_object = dict() and dict_object = {}

The problem here is [{}] * 2 will generate a list with 2 elements which are reference to a single object. [{} for x in range(2)] will generate a list with two elements which are reference two distinct objects.

Replacing {} with dict() will get the same result.

Jacky1205
  • 3,273
  • 3
  • 22
  • 44
1

Both the dictionary in the list pointing to same object, Hence modifying one will will change others also

>>> list_of_dict = [{}]*2
>>> id(list_of_dict[0])
50030176
>>> id(list_of_dict[1])
50030176

When you created two empty dictionary by using dict(), dict() return different object every time

>>> d1 = dict()
>>> d2 = dict()
>>> id(d1)
50074656
>>> id(d2)
50074512
AlokThakur
  • 3,599
  • 1
  • 19
  • 32
  • 1
    This answer makes it seem like the choice of `dict()` in the second example is relevant. It isn't. `d1 = {}` and `d2 = {}` would have the same result as using `dict()`, it's *multiplying* a `list` containing just one `dict` that causes the problem. – ShadowRanger Sep 25 '21 at 04:08