Understanding the fromkeys Method and its Limitations
When initializing a dictionary using the fromkeys method, it is important to be aware of its behavior with single-element arguments. Passing a list as the second argument will result in all dictionary values referencing the same list object.
Avoiding Unintended Sharing: Alternative Approaches
To prevent unintended sharing of values, consider using alternative methods:
Dict Comprehension (Python 2.7 ):
data = {k: [] for k in range(2)}
List Comprehension with Dict Constructor:
data = dict([(k, []) for k in range(2)])
Generator Expression with Dict (Python 2.4-2.6):
data = dict((k, []) for k in range(2))
Simple Example: Adding a Value to a Specific Key
The following code demonstrates the intended behavior:
data = {0: [], 1: []} data[1].append('hello') print(data) # Output: {0: [], 1: ['hello']}
By using one of the suggested methods, you can initialize a dictionary of empty lists and modify individual key values without affecting the others.
The above is the detailed content of How Can I Avoid Shared References When Using Python's `fromkeys` Method?. For more information, please follow other related articles on the PHP Chinese website!