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
Release: 2024-11-26 05:43:09
Original
365 people have browsed it

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)}
Copy after login

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)])
Copy after login

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

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

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!

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