Home  >  Article  >  Backend Development  >  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
Patricia ArquetteOriginal
2024-10-25 15:56:02248browse

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]}

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: []}

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)

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

>>> xs[0] is a and xs[1] is a
True

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))

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!

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