Does Python make a copy of objects on assignment?
As danben previously said, you're just copying the same dict into 3 variables, so that each one refers to the same object.
To get the behaviour you want, you should instantiate a different dict in each variable:
>>> dict_a, dict_b, dict_c = {}, {}, {}
>>> dict_c['hello'] = 'goodbye'
>>> print dict_a
{}
>>> print dict_b
{}
>>> print dict_c
{'hello': 'goodbye'}
>>>
This is because in Python, variables (names) are just references to individual objects. When you assign dict_a = dict_b
, you are really copying a memory address (or pointer, if you will) from dict_b
to dict_a
. There is still one instance of that dictionary.
To get the desired behavior, use either the dict.copy
method, or use copy.deepcopy
if your dict may have nested dicts or other nested objects.
>>> a = {1:2}
>>> b = a.copy()
>>> b
{1: 2}
>>> b[3] = 4
>>> a
{1: 2}
>>> b
{1: 2, 3: 4}
>>>
Even though
>>> dict_a, dict_b, dict_c = {}, {}, {}
is the right way to go in most cases, when it get more than 3 it looks weird
Imagine
>>> a, b, c, d, e, f = {}, {}, {}, {}, {}, {}
In cases where I wanna initialize more than 3 things, I use
>>> a, b, c, d, e, f, = [dict() for x in range(6)]