Home > Backend Development > Python Tutorial > How to Properly Initialize a Dictionary with Empty Lists in Python?

How to Properly Initialize a Dictionary with Empty Lists in Python?

DDD
Release: 2024-11-25 08:36:47
Original
227 people have browsed it

How to Properly Initialize a Dictionary with Empty Lists in Python?

Dictionary Initialization with Empty Lists in Python

In Python, creating a dictionary of empty lists can be achieved through various approaches. However, the fromkeys method may not produce the desired outcome as it creates a single list object referenced by all dictionary keys.

Consider the following example:

data = {}
data = data.fromkeys(range(2), [])
data[1].append('hello')
print(data)
Copy after login

Expected Result: {0: [], 1: ['hello']}
Actual Result: {0: ['hello'], 1: ['hello']}

Cause:

When using fromkeys, the second argument ([]) is treated as a single list object, which is referenced by all keys in the resulting dictionary. Any modifications to any key will propagate to all others.

Solution:

To create a dictionary of independent empty lists, use a dict comprehension:

In Python 2.7 or above:

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

In Python versions prior to 2.7:

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

Alternatively, in Python 2.4 - 2.6, use a generator expression:

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

These approaches ensure that each key in the dictionary references a distinct empty list object, allowing for independent modifications and addressing of dictionary values.

The above is the detailed content of How to Properly Initialize a Dictionary with Empty Lists in Python?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template