Dictionary of lists strange behaviour

Matteo Landi landimatte at gmail.com
Tue Nov 9 15:24:11 CET 2010


On Tue, Nov 9, 2010 at 3:14 PM, Ciccio <franapoli at gmail.com> wrote:
> Hi all,
>
> hope you can help me understanding why the following happens:
>
> In [213]: g = {'a': ['a1','a2'], 'b':['b1','b2']}
> In [214]: rg = dict.fromkeys(g.keys(),[])

The argument you pass which is used to fill the values of the new
dict, is created once; this means that the empty list is shared
between all the keys of the dict.
I think you need to create the new dict  by hand.

Regards,
Matteo

> In [215]: rg
> Out[215]: {'a': [], 'b': []}
> In [216]: rg['a'].append('x')
> In [217]: rg
> Out[217]: {'a': ['x'], 'b': ['x']}
>
> What I meant was appending 'x' to the list pointed by the key 'a' in the
> dictionary 'rg'. Why rg['b'] is written too?
>
> Thanks.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Matteo Landi
http://www.matteolandi.net/



More information about the Python-list mailing list