Here are a few title options, playing on the \'mystery\' and \'unexpected behavior\' aspects: * Why Does `dict.fromkeys` Act So Strangely with Mutable Objects? * The Mystery of `d

DDD
Release: 2024-10-26 14:52:03
Original
923 people have browsed it

Here are a few title options, playing on the

Unveiling the Mystery of dict.fromkeys and Mutable Objects

The dict.fromkeys function in Python can behave unexpectedly when used with mutable objects, as demonstrated in the following example:

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

The Puzzling Behavior

This behavior seemingly contradicts that of dictionary comprehensions, which preserve distinct values for each key:

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

Understanding the Discrepancy

The key difference lies in the way these two methods create dictionaries. In Python 2.6 (and earlier), dict.fromkeys references the same mutable object for all keys, while dictionary comprehensions create distinct objects for each key.

The result is that when xs[0] is mutated in the first example, the change is reflected in xs[1] because they refer to the same list object. In contrast, in the second example, the lists are distinct, so mutating xs[0] does not affect xs[1].

Avoiding the Surprise

To avoid this unexpected behavior, it is recommended to use dictionary comprehensions whenever possible. If dictionary comprehensions are not available (e.g., in Python 2.6), creating distinct objects using a generator expression with the dict function is an alternative:

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

The above is the detailed content of Here are a few title options, playing on the \'mystery\' and \'unexpected behavior\' aspects: * Why Does `dict.fromkeys` Act So Strangely with Mutable Objects? * The Mystery of `d. 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
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!