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.