defaultdict.fromkeys returns a surprising defaultdict

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Jun 3 23:09:41 EDT 2008


En Tue, 03 Jun 2008 17:11:06 -0300, Matthew Wilson <matt at tplus1.com>  
escribió:

> I used defaultdict.fromkeys to make a new defaultdict instance, but I
> was surprised by behavior:
>
>     >>> b = defaultdict.fromkeys(['x', 'y'], list)
>    >>> b
>     defaultdict(None, {'y': <type 'list'>, 'x': <type 'list'>})
>    >>> b['x']
>     <type 'list'>
>    >>> b['z']
>     ------------------------------------------------------------
>     Traceback (most recent call last):
>       File "<ipython console>", line 1, in <module>
>     KeyError: 'z'
>
> I think that what is really going on is that fromdict makes a regular
> dictionary, and then hands it off to the defaultdict class.
>
> I find this confusing, because now I have a defaultdict that raises a
> KeyError.
>
> Do other people find this intuitive?
>
> Would it be better if defaultdict.fromkeys raised a
> NotImplementedException?
>
> Or would it be better to redefine how defaultdict.fromkeys works, so
> that it first creates the defaultdict, and then goes through the keys?

That looks reasonable. It appears there is currently no way to do what you  
want (apart from using a for loop to set each key)

-- 
Gabriel Genellina




More information about the Python-list mailing list