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

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

Patricia Arquette
Release: 2024-10-25 16:27:02
Original
257 people have browsed it

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

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

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

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

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!

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