Home >Backend Development >Python Tutorial >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)
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)}
In Python versions prior to 2.7:
data = dict([(k, []) for k in range(2)])
Alternatively, in Python 2.4 - 2.6, use a generator expression:
data = dict((k, []) for k in range(2))
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!