"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why does `dict.fromkeys()` create shared mutable objects in Python?

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

Published on 2024-11-08
Browse:492

 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:

xs = dict.fromkeys(range(2), [])
xs[0].append(1)
print(xs)

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:

xs = {i: [] for i in range(2)}
xs[0].append(1)
print(xs)

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:

a = []
xs = dict.fromkeys(range(2), a)

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:

xs = dict((i, []) for i in range(2))
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3