Unveiling the Mystery of dict.fromkeys and Mutable Objects
The dict.fromkeys function in Python can behave unexpectedly when used with mutable objects, as demonstrated in the following example:
<code class="python">xs = dict.fromkeys(range(2), []) xs[0].append(1) # xs now contains {0: [1], 1: [1]} instead of {0: [1], 1: []}</code>
The Puzzling Behavior
This behavior seemingly contradicts that of dictionary comprehensions, which preserve distinct values for each key:
<code class="python">xs = {i: [] for i in range(2)} xs[0].append(1) # xs still contains {0: [1], 1: []}</code>
Understanding the Discrepancy
The key difference lies in the way these two methods create dictionaries. In Python 2.6 (and earlier), dict.fromkeys references the same mutable object for all keys, while dictionary comprehensions create distinct objects for each key.
The result is that when xs[0] is mutated in the first example, the change is reflected in xs[1] because they refer to the same list object. In contrast, in the second example, the lists are distinct, so mutating xs[0] does not affect xs[1].
Avoiding the Surprise
To avoid this unexpected behavior, it is recommended to use dictionary comprehensions whenever possible. If dictionary comprehensions are not available (e.g., in Python 2.6), creating distinct objects using a generator expression with the dict function is an alternative:
<code class="python">xs = dict((i, []) for i in range(2))</code>
The above is the detailed content of Here are a few title options, playing on the \'mystery\' and \'unexpected behavior\' aspects: * Why Does `dict.fromkeys` Act So Strangely with Mutable Objects? * The Mystery of `d. For more information, please follow other related articles on the PHP Chinese website!