Home > Backend Development > Python Tutorial > Why Does `dict.fromkeys()` Create Shared Lists, and How Can I Avoid It?

Why Does `dict.fromkeys()` Create Shared Lists, and How Can I Avoid It?

Linda Hamilton
Release: 2024-11-25 01:54:11
Original
293 people have browsed it

Why Does `dict.fromkeys()` Create Shared Lists, and How Can I Avoid It?

Fromkeys Caveats: Understanding the Behavior of Dictionary Initialization

In Python, the dict.fromkeys() method is commonly used to create a dictionary with specified keys assigned to empty lists. However, misinterpretation of its behavior has led to unexpected results.

Why fromkeys() Is Tricky

When an empty list [] is provided as the second argument to dict.fromkeys(), all values in the resulting dictionary point to the same list object. This means that any modification to one value affects all values.

Alternative Solutions

To address this issue, the following solutions are recommended:

  • Use a Dictionary Comprehension:

    In Python 2.7 or above, a dictionary comprehension is the most concise and readable solution:

    data = {k: [] for k in range(2)}
    Copy after login
  • Use a List Comprehension with dict():

    In earlier Python versions, a list comprehension can be passed to the dict() constructor:

    data = dict([(k, []) for k in range(2)])
    Copy after login
  • Use a Generator Expression with dict():

    In Python 2.4-2.6, a generator expression can be used with dict(), and parentheses can be omitted:

    data = dict((k, []) for k in range(2))
    Copy after login

Example

The following example illustrates the difference between the default behavior of fromkeys() and the recommended solutions:

# Default behavior of fromkeys()
data = {}
data = data.fromkeys(range(2), [])
data[1].append('hello')
print(data)  # Output: {0: ['hello'], 1: ['hello']}

# Using a dictionary comprehension
data = {k: [] for k in range(2)}
data[1].append('hello')
print(data)  # Output: {0: [], 1: ['hello']}
Copy after login

By understanding the nuances of fromkeys(), developers can effectively create dictionaries of empty lists and maintain individual key addressing.

The above is the detailed content of Why Does `dict.fromkeys()` Create Shared Lists, and How Can I Avoid It?. For more information, please follow other related articles on the PHP Chinese website!

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