defaultdict.fromkeys returns a surprising defaultdict

Raymond Hettinger python at rcn.com
Wed Jun 4 13:36:51 CEST 2008


On Jun 3, 1: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'>})

One other thought:  Even after correcting the code as shown in other
posts, I don't think you're on the right track.  If you know the full
population of keys at the outset and just want them to all have an
initial value, the defaultdict isn't the right tool.  Instead, just
populate a regular dict in usual way:

    >>> dict((k, []) for k in 'xyz')
    {'y': [], 'x': [], 'z': []}

The time to use defaultdict is when you *don't* want to pre-populate a
dict.  The factory gets run during the lookup phase and creates your
default just-in-time for use:

>>> d = defaultdict(list)
>>> for k in 'zyzygy':
	d[k].append(1)  # empty list created on lookup if needed
>>> d
defaultdict(<type 'list'>, {'y': [1, 1, 1], 'z': [1, 1], 'g': [1]})


Raymond



More information about the Python-list mailing list