Home >Backend Development >Python Tutorial >How to Avoid Shared List References When Initializing Empty List Dictionaries in Python?

How to Avoid Shared List References When Initializing Empty List Dictionaries in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-11-26 05:43:09367browse

How to Avoid Shared List References When Initializing Empty List Dictionaries in Python?

Initialization of Empty List Dictionary in Python

Attempting to create a dictionary of lists by using the fromkeys method may result in unexpected behavior where all dictionary keys are updated when appending to one key. This is because fromkeys creates a single list object and references it as the value for all keys.

To resolve this issue, use a dictionary comprehension:

data = {k: [] for k in range(2)}

This comprehension creates a new list object for each key, ensuring that each key has its own independent list.

Alternatively, in Python versions prior to 2.7, use a list comprehension passed to the dict constructor:

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

or, in Python 2.4-2.6, a generator expression can be passed to dict:

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

The above is the detailed content of How to Avoid Shared List References When Initializing Empty List Dictionaries in Python?. 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