Dictionary of lists strange behaviour

Terry Reedy tjreedy at udel.edu
Tue Nov 9 19:43:43 CET 2010

On 11/9/2010 12:19 PM, Ciccio wrote:
> Il 09/11/2010 16:47, Terry Reedy ha scritto:
>> 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?
> It isn't since I erroneously assumed that a clone of the object would be
> made in both cases.

I can see how you might think that, especially if you have experience 
with other languages where that would be usual. In Python, the general 
policy is to not copy objects unless explicitly requested. None, False, 
and True cannot be copied. There is essentially never a reason to copy a 
number or string or tuple.

I believe dict.fromkeys is more usually given None or 0 or '' as value 
initializer. List *is* useful as an initializer for 

Terry Jan Reedy

More information about the Python-list mailing list