defaultdict.fromkeys returns a surprising defaultdict

Thomas Bellman bellman at lysator.liu.se
Wed Jun 4 07:11:50 CEST 2008


"Gabriel Genellina" <gagsl-py2 at yahoo.com.ar> wrote:

> That looks reasonable. It appears there is currently no way to do what you
> want (apart from using a for loop to set each key)

You can do this:

    >>> d = defaultdict.fromkeys(['x', 'y'], 0)
    >>> d.default_factory = list
    >>> d
    defaultdict(<type 'list'>, {'y': 0, 'x': 0})
    >>> d['z']
    []
    >>> d
    defaultdict(<type 'list'>, {'y': 0, 'x': 0, 'z': []})

The keys you give to the fromkeys() method will all be set to the
same object (the integer zero, in the case above), though, which
might not be what you want.


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"Don't tell me I'm burning the candle at both ! bellman @ lysator.liu.se
 ends -- tell me where to get more wax!!"     ! Make Love -- Nicht Wahr!



More information about the Python-list mailing list