Python: Appending to a list, which is value of a dictionary
<p>Here is the code, which I would like to understand. I am creating a dict using elements of a list as keys and another list as default values. Then update this dict with another one. Finally, I would like to append to the list within dict. The append is happening multiple times for some of the elements. I would like append to happy only once for each of the values of dict. </p>

<pre><code>l=['a','b','c']
bm=dict.fromkeys(l,['-1','-1'])
u={'a':['Q','P']}
bm.update(u)
bm
# {'a': ['Q', 'P'], 'c': ['-1', '-1'], 'b': ['-1', '-1']}
for k in bm.keys():
    bm[k].append('DDD')
bm
# {'a': ['Q', 'P', 'DDD'], 'c': ['-1', '-1', 'DDD', 'DDD'], 'b': ['-1', '-1', 'DDD', 'DDD']}
</code></pre>

<p>I was expecting appending <code>DDD</code> to happen once for <code>c</code> and <code>b</code> like this:</p>

<pre><code>{'a': ['Q', 'P', 'DDD'], 'c': ['-1', '-1', 'DDD'], 'b': ['-1', '-1', 'DDD']}
</code></pre>

<p>this</p>

<pre><code>bm=dict.fromkeys(l,['-1','-1'])
</code></pre>

<p>Is reusing the same list <code>['-1','-1']</code> for all keys, which explains the effect you're witnessing.</p>

<p>to achieve what you want you could do this with a <em>dict comprehension</em></p>

<pre><code>bm = {x:[-1,1] for x in ['a','b','c']}
</code></pre>

<p>(the loop within the dict comp ensures that a different instance of the <code>[-1,1]</code> list is created for each value, which guarantees independence)</p>

<p>Full example:</p>

<pre><code>bm = {x:[-1,1] for x in ['a','b','c']}

u={'a':['Q','P']}
bm.update(u)
print(bm)
for k in bm.keys():
    bm[k].append('DDD')

print(bm)
</code></pre>

<p>result:</p>

<pre><code>{'c': [-1, 1], 'a': ['Q', 'P'], 'b': [-1, 1]}
{'c': [-1, 1, 'DDD'], 'a': ['Q', 'P', 'DDD'], 'b': [-1, 1, 'DDD']}
</code></pre>

<p>Note: if you want that all accessed keys create a default value when not present you can use <code>defaultdict</code> with a lambda which creates a different instance of <code>['-1','-1']</code> every time.</p>

<pre><code>from collections import defaultdict
bm = defaultdict(lambda : ['-1','-1'])
</code></pre>

python