Dictionary Creation with fromkeys and Mutable Objects: A Surprising Twist
The fromkeys method in Python is a convenient way to create a dictionary from a sequence of keys, all mapped to a specified value. However, when using mutable objects as the value, an unexpected behavior can occur.
The Curiosity
Consider the following example in Python 2.6 and 3.2:
<code class="python">xs = dict.fromkeys(range(2), []) xs[0].append(1) print(xs)</code>
To our surprise, modifying the list associated with the first key ([0]) also affects the list associated with the second key ([1]). This can be puzzling since we expect each key to have its own independent value.
The Revelation
The reason for this peculiar behavior lies in the fact that the fromkeys method creates a new dictionary with references to the same mutable object, rather than creating separate copies. In other words, all dictionary entries point to the same underlying mutable object.
The Solution
To avoid this issue, we can use dict comprehensions, which create a new list for each dictionary key:
<code class="python">xs = {i: [] for i in range(2)} xs[0].append(1) print(xs)</code>
In Python 2.6 and older, we can achieve similar behavior by using dict() with a generator expression:
<code class="python">xs = dict((i, []) for i in range(2))</code>
This alternative method also creates separate lists for each dictionary key.
Conclusion
Understanding the nuances of dictionary creation with mutable objects is essential for preventing unexpected behavior and maintaining data integrity in Python code. By choosing the appropriate method, we can ensure that dictionary entries are properly isolated and avoid unwanted side effects.
The above is the detailed content of Why Does `fromkeys` with Mutable Objects Create Shared Values in Python Dictionaries?. For more information, please follow other related articles on the PHP Chinese website!