Home  >  Article  >  Backend Development  >  Why does `dict.fromkeys()` create shared mutable objects in Python?

Why does `dict.fromkeys()` create shared mutable objects in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 16:27:02148browse

 Why does `dict.fromkeys()` create shared mutable objects in Python?

Dictionary Creation and Mutable Objects: Surprising Behavior with fromkeys

When creating dictionaries using dict.fromkeys() in Python, an unexpected situation may arise when mutable objects are employed as values. Consider the following example:

<code class="python">xs = dict.fromkeys(range(2), [])
xs[0].append(1)
print(xs)</code>

Despite creating two separate list objects as values for the dictionary keys 0 and 1, adding an element to the list at index 0 also adds it to the list at index 1. This occurs because fromkeys binds each key to the same reference of the mutable object, resulting in shared modifications.

In contrast, dictionary comprehensions in Python 3.2 exhibit different behavior:

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

Here, each key is bound to a distinct list object. Appending an element to the list at index 0 does not affect the list at index 1.

Why the Difference?

The behavior of fromkeys can be understood by considering the following equivalent code:

<code class="python">a = []
xs = dict.fromkeys(range(2), a)</code>

Each key in the resulting dictionary references the same a object, leading to the observed shared modifications.

To achieve the desired behavior of distinct mutable objects for each key, use dictionary comprehensions or, for Python 2.6 and earlier without dictionary comprehensions, use dict() with a generator expression:

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

The above is the detailed content of Why does `dict.fromkeys()` create shared mutable objects in Python?. 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