1

Let's create a nested dictionary with the built-in method dict.fromkeys():

dct = dict.fromkeys(["d1", "d2"], {})
dct["d1"]["x"] = 9
print(dct)
# {'d2': {'x': 9}, 'd1': {'x': 9}}

Huh? That's strange, I only wanted to change dct["d1"]!

This however works:

dct = {"d1": {}, "d2": {}}
dct["d1"]["x"] = 9
print(dct)
# {'d2': {}, 'd1': {'x': 9}}

What's going on here? Why's {"d1": {}, "d2": {}} not equivalent to dict.fromkeys(["d1", "d2"], {})? I'm on Python 2.7 if that matters.

MERose
  • 4,048
  • 7
  • 53
  • 79
  • 1
    `dict.fromkeys()` does not create copies of the second argument. You are sharing *one single dictionary* between all the keys. – Martijn Pieters Mar 30 '16 at 14:39

0 Answers0