Home  >  Article  >  Backend Development  >  Why Does `dict.fromkeys` With Mutable Values Create Shared Objects?

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

Susan Sarandon
Susan SarandonOriginal
2024-10-26 03:16:27142browse

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>

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>

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>

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>

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!

Statement:
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