Why Does `fromkeys` with Mutable Objects Create Shared Values in Python Dictionaries?

Patricia Arquette
Release: 2024-10-26 11:05:29
Original
338 people have browsed it

 Why Does `fromkeys` with Mutable Objects Create Shared Values in Python Dictionaries?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template