Dictionary of lists strange behaviour
Terry Reedy
tjreedy at udel.edu
Tue Nov 9 10:47:45 EST 2010
On 11/9/2010 9:14 AM, 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(),[])
If you rewrite this as
bl = []
rg = dict.fromkeys(g.keys(),bl)
is the answer any more obvious?
> 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?
--
Terry Jan Reedy
More information about the Python-list
mailing list