When you use fromkeys
, what is happening is the dictionary is being created, and all its keys have the same object as their value.
What this means is that both d2["foo"]
and d2["bar"]
refer to the same object. It is the same object, not just an identical one. Therefore, modifying it via one key changes it across all other keys.
This is a lot more noticeable if you use a custom object:
class MyClass:
def __init__(self):
pass
a = MyClass()
d = dict.fromkeys(["foo", "bar"], a)
Printing d
yields the following output:
{'foo': <__main__.MyClass object at 0x0000000004699AC8>, 'bar': <__main__.MyClass object at 0x0000000004699AC8>}
Notice how the memory addresses are the same, because it is the same object.
In d1
however, you do not assign the same object to both keys. Rather, you assign two separate identical ones (empty lists). Therefore modifying one does not change the other.