defaultdict.fromkeys returns a surprising defaultdict

Matthew Wilson matt at tplus1.com
Tue Jun 3 22:11:06 CEST 2008


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



More information about the Python-list mailing list