I would expect that the following code would just initialise the dict_a
, dict_b
and dict_c
dictionaries. But it seams to have a copy through effect:
dict_a = dict_b = dict_c = {}
dict_c['hello'] = 'goodbye'
print dict_a
print dict_b
print dict_c
As you can see the result is as follows:
{'hello': 'goodbye'}
{'hello': 'goodbye'}
{'hello': 'goodbye'}
Why does that program give the previous result, When I would expect it to return:
{}
{}
{'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) fromdict_b
todict_a
. There is still one instance of that dictionary.To get the desired behavior, use either the
dict.copy
method, or usecopy.deepcopy
if your dict may have nested dicts or other nested objects.Even though
is the right way to go in most cases, when it get more than 3 it looks weird
Imagine
In cases where I wanna initialize more than 3 things, I use
Caution: Do not use
[{} for x in range(6)]
Your first assignment assigns the same dictionary object to the variables dict_a, dict_b, and dict_c. It is equivalent to dict_c = {}; dict_b = dict_c; dict_a = dict_c.
As danben previously said, you're just copying the same dict into 3 variables, so that each one reffers to the same object.
To get the behaviour you want, you should instanciate a different dict in each variable: