YamiOmar88
YamiOmar88

Reputation: 1476

Update value in nested dictionary - Python

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?

Upvotes: 2

Views: 994

Answers (1)

UltraInstinct
UltraInstinct

Reputation: 44444

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)}

Upvotes: 5

Related Questions