In Python 2.6 and 3.2, the behavior of dict.fromkeys with mutable objects can be surprising. When a list is used as the value, modifying one entry in the dictionary affects every other entry, as demonstrated below:
>>> xs = dict.fromkeys(range(2), []) >>> xs {0: [], 1: []} >>> xs[0].append(1) >>> xs {0: [1], 1: [1]}
However, this behavior does not occur with Python 3.2's dict comprehensions:
>>> xs = {i:[] for i in range(2)} >>> xs {0: [], 1: []} >>> xs[0].append(1) >>> xs {0: [1], 1: []}
The apparent reason for fromkeys' behavior is that each entry in the resulting dictionary references the same object. Modifying the object through one entry affects all the others. This can be clarified by creating the dictionary manually:
>>> a = [] >>> xs = dict.fromkeys(range(2), a)
This demonstrates that the dictionary entries all reference the same object:
>>> xs[0] is a and xs[1] is a True
To avoid this behavior, use dict comprehensions or, if using Python 2.6 or earlier, use dict with a generator expression:
xs = dict((i, []) for i in range(2))
The above is the detailed content of Why Does Python's `dict.fromkeys` With Mutable Values Cause Unexpected Behavior?. For more information, please follow other related articles on the PHP Chinese website!