Skip to content


defaultdict.fromkeys does not play nice.

I use defaultdicts a lot when I’m grouping elements into a dictionary of lists. Here’s a simple example:


>>> a = defaultdict(list)

>>> a['x']
[]

>>> a['y'].append('yellow')

>>> a
defaultdict(<type 'list'>, {'y': ['yellow'], 'x': []})

Now here’s where I got silly. I used defaultdict.fromkeys to prepopulate the ‘x’ and ‘y’ key right away, because I know I needed those:

>>> 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'

Wowsa! b calls itself a defaultdict, but it is not a defaultdict.

I haven’t really thought this through, but this behavior is so unexpected that I would prefer that defaultdict.fromkeys raised a NotImplementedError.

Posted in Programming, Python.

Viewing 5 Comments

 
close Reblog this comment
blog comments powered by Disqus