Home > Backend Development > Python Tutorial > Why Does Python\'s `dict.fromkeys` With Mutable Values Cause Unexpected Behavior?

Why Does Python\'s `dict.fromkeys` With Mutable Values Cause Unexpected Behavior?

Patricia Arquette
Release: 2024-10-25 15:56:02
Original
341 people have browsed it

Why Does Python's `dict.fromkeys` With Mutable Values Cause Unexpected Behavior?

Dictionary Creation with fromkeys and Mutable Objects: An Unexpected Surprise

In Python 2.6 and 3.2, the behavior of dict.fromkeys with mutable objects can be surprising. When a list is used as the value, modifying one entry in the dictionary affects every other entry, as demonstrated below:

>>> xs = dict.fromkeys(range(2), [])
>>> xs
{0: [], 1: []}
>>> xs[0].append(1)
>>> xs
{0: [1], 1: [1]}
Copy after login

However, this behavior does not occur with Python 3.2's dict comprehensions:

>>> xs = {i:[] for i in range(2)}
>>> xs
{0: [], 1: []}
>>> xs[0].append(1)
>>> xs
{0: [1], 1: []}
Copy after login

Reason for fromkeys' Behavior

The apparent reason for fromkeys' behavior is that each entry in the resulting dictionary references the same object. Modifying the object through one entry affects all the others. This can be clarified by creating the dictionary manually:

>>> a = []
>>> xs = dict.fromkeys(range(2), a)
Copy after login

This demonstrates that the dictionary entries all reference the same object:

>>> xs[0] is a and xs[1] is a
True
Copy after login

Mitigating the Behavior with Dict Comprehensions

To avoid this behavior, use dict comprehensions or, if using Python 2.6 or earlier, use dict with a generator expression:

xs = dict((i, []) for i in range(2))
Copy after login

The above is the detailed content of Why Does Python\'s `dict.fromkeys` With Mutable Values Cause Unexpected Behavior?. 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