Appending to a list, which is value of a dictionary

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Sat Oct 15 12:09:34 EDT 2016


Uday J writes:

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

It happened once for 'c' and once for 'd' but bm['c'] and bm['d'] are
the same list so it happened twice for that list.



More information about the Python-list mailing list