defaultdict.fromkeys returns a surprising defaultdict

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Jun 3 22:59:34 EDT 2008


En Tue, 03 Jun 2008 17:18:59 -0300, Chris <cwitts at gmail.com> escribió:
> 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 find this confusing, because now I have a defaultdict that raises a
>> KeyError.
>>
> To me it's intuitive for it to raise a KeyError, afterall the Key
> isn't in the dictionary.

But the idea behind a defaultdict is to *not* raise a KeyError but use the  
default_factory to create missing values. (Unfortunately there is no way  
to provide a default_factory when using fromkeys).

-- 
Gabriel Genellina




More information about the Python-list mailing list