I created a dictionary as follows:
gP = dict.fromkeys(range(6), {'a': None, 'b': None, 'c': None, 'd': None})
Now, when I try to modify a value doing:
gP[0]['a'] = 1
for some reason, all the values of a (regardless of the key they belong to) change to 1 as shown below:
{0: {'a': 1, 'b': None, 'c': None, 'd': None},
1: {'a': 1, 'b': None, 'c': None, 'd': None},
2: {'a': 1, 'b': None, 'c': None, 'd': None},
3: {'a': 1, 'b': None, 'c': None, 'd': None},
4: {'a': 1, 'b': None, 'c': None, 'd': None},
5: {'a': 1, 'b': None, 'c': None, 'd': None}}
What I am doing wrong? What's the proper assignment statement?
解决方案
As @deceze said, Python doesn't make copies. You are referencing the same dict in all the value parts of the key-value pairs.
An alternative would be:
gP = {x: {'a': None, 'b': None, 'c': None, 'd': None} for x in range(6)}
Update: There is a much cleaner version of this answer by @Chris_Rands:
{x: dict.fromkeys('abcd') for x in range(6)}