Dictionary of lists strange behaviour
Jean-Michel Pichavant
jeanmichel at sequans.com
Tue Nov 9 09:43:05 EST 2010
Ciccio 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(),[])
> 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.
rg = dict.fromkeys(g.keys(),[])
you are intialising the content with the same object [].
write instead
for key in g:
rg[key] = [] # python create a new list everytime it hits this line
For the same reason you never assign an empty list to default parameters
value:
In [37]: def a(p=[]):
....: return p
....:
In [38]: a1 = a()
In [39]: a2 = a()
In [40]: id(a1) ; id(a2)
Out[40]: 161119884
Out[40]: 161119884
Jean-Michel
More information about the Python-list
mailing list