The Problem
I am creating a dictionary with empty lists as values in the following way.
>>> words = dict.fromkeys(['coach', 'we', 'be'], [])
The dictionary looks like this.
>>> words
{'coach': [], 'be': [], 'we': []}
When I append a value to one list, the value is appended to all of them as in this example.
>>> words['coach'].append('test')
{'coach': ['test'], 'be': ['test'], 'we': ['test']}
The Question
My question has two parts. First, why is this happening? Second, what can I do about it? That is, how can I append a value to only one list?
I imagine that in creating the dictionary, I made all lists point to the same object. But I don't understand how that can be because when I input 0
instead of []
in dictionary creation and then add values instead of append them, the values behave differently as if they point to distinct objects.
I would appreciate any input. Thank you in advance!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…