Why Does `dict.fromkeys` With Mutable Values Create Shared Objects?

Susan Sarandon
Release: 2024-10-26 03:16:27
Original
158 people have browsed it

Why Does `dict.fromkeys` With Mutable Values Create Shared Objects?

Mutable Objects and Dictionary Creation with fromkeys

The behavior observed in using dict.fromkeys to create dictionaries with mutable objects, such as lists, can be surprising at first. The following example demonstrates the issue:

<code class="python">xs = dict.fromkeys(range(2), [])
xs[0].append(1)
print(xs)  # Outputs: {0: [1], 1: [1]}</code>
Copy after login

In this case, we create a dictionary with two keys (0 and 1) and an empty list for each value. However, when we append an element to the list associated with key 0, it also appears in the list associated with key 1.

To understand this behavior, it's important to note that dict.fromkeys shares the same value object between all keys. In our example, both xs[0] and xs[1] point to the same list object, as seen below:

<code class="python">print(xs[0] is xs[1])  # Outputs: True</code>
Copy after login

Therefore, any modifications made to the list through xs[0] are also reflected in xs[1] because they refer to the same underlying object.

In contrast, using a dictionary comprehension to create a dictionary with mutable objects results in each value being a separate object:

<code class="python">xs = {i: [] for i in range(2)}
xs[0].append(1)
print(xs)  # Outputs: {0: [1], 1: []}</code>
Copy after login

In this case, xs[0] and xs[1] are not the same object, so modifying xs[0] does not affect xs[1].

In Python 2.6 or earlier, when dictionary comprehensions are not available, you can use a generator expression with dict() to achieve the same behavior as a dictionary comprehension:

<code class="python">xs = dict((i, []) for i in range(2))</code>
Copy after login

The above is the detailed content of Why Does `dict.fromkeys` With Mutable Values Create Shared Objects?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!