defaultdict.fromkeys returns a surprising defaultdict

MRAB google at mrabarnett.plus.com
Wed Jun 4 02:02:54 CEST 2008


On Jun 3, 9: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.
>
The statement:

b = defaultdict.fromkeys(['x', 'y'], list)

is equivalent to:

b = defaultdict()
for i in ['x', 'y']:
    b[i] = list

so there's no default_factory and therefore the defaultdict will
behave like a dict. Perhaps there could be an optional third argument
to provide a default_factory.



More information about the Python-list mailing list