2

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?

2
  • 1
    You're only creating one dict. Python doesn't make copies of it for you. Commented Apr 20, 2017 at 8:13
  • Could you elaborate? I don't understand how to fix it from your answer, @deceze. Commented Apr 20, 2017 at 8:15

1 Answer 1

5

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)}
Sign up to request clarification or add additional context in comments.

4 Comments

Shorter would be {x: dict.fromkeys('abcd') for x in range(6)}; or probably faster to take the dict.fromkeys outside the loop
@Chris_Rands: You should probably put that out as a separate answer. I like it better than mine. :)
You can add it to your answer :)
Please post someone, It's a nice attempt.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.