Unwanted behaviour from dict.fromkeys [duplicate]

The second argument to dict.fromkeys is just a value. You’ve created a dictionary that has the same set as the value for every key. Presumably you understand the way this works:

>>> a = set()
>>> b = a
>>> b.add(1)
>>> b
set([1])
>>> a
set([1])

you’re seeing the same behavior there; in your case, x[0], x[1], x[2] (etc) are all different ways to access the exact same set object.

This is a bit easier to see with objects whose string representation includes their memory address, where you can see that they’re identical:

>>> dict.fromkeys(range(2), object())
{0: <object object at 0x1001da080>,
 1: <object object at 0x1001da080>}

Leave a Comment