Appending to a list, which is value of a dictionary

Uday J udayj2121 at gmail.com
Sat Oct 15 08:35:34 EDT 2016


Hi,

Here is the code, which I would like to understand.

>>> 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']}

I was expecting appending DDD to happen once for 'c' and 'b'.
{'a': ['Q', 'P', 'DDD'], 'c': ['-1', '-1', 'DDD'], 'b': ['-1', '-1', 'DDD']}



More information about the Python-list mailing list