Dictionary of lists strange behaviour

Dave Angel davea at ieee.org
Tue Nov 9 16:05:44 CET 2010

On 2:59 PM, 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.
The second argument to the fromkeys() method is an empty list object.  
So that object is the value for *both* the new dictionary items.  It 
does not make a new object each time, it uses the same one.

You can check this for yourself, by doing
    id(rg["a"])      and  id(rg["b"])

I'd do something like :

rg = {}
for key in g.keys():
       rg[key] = []


More information about the Python-list mailing list