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.
Add New Comment
Viewing 5 Comments
Thanks. Your comment is awaiting approval by a moderator.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Add New Comment