defaultdict.fromkeys returns a surprising defaultdict

Chris cwitts at gmail.com
Tue Jun 3 16:18:59 EDT 2008


On Jun 3, 10:11 pm, Matthew Wilson <m... at tplus1.com> wrote:
> 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?
>
> All comments welcome.  If I get some positive feedback, I'm going to try
> to submit a patch.
>
> Matt

To me it's intuitive for it to raise a KeyError, afterall the Key
isn't in the dictionary.



More information about the Python-list mailing list