Concise idiom to initialize dictionaries

Jeff Epler jepler at unpythonic.net
Tue Nov 9 13:37:40 EST 2004


The documentation (docs.python.org, not help(locals)) makes it clear
that this is not intended to work:

 locals()
     Update and return a dictionary representing the current local
     symbol table. Warning: The contents of this dictionary should not
     be modified; changes may not affect the values of local variables
     used by the interpreter. 

Perhaps you want a dict of dicts.
    d = dict([(s, {}) for s in 'abc...z'])
now refer to d['a'][key] instead of a[key]

Python has good reasons to forbid the modification of locals().  The
most important may be that for each function, static analysis determines
whether a particular name is local or not:  A name is local if it is
assigned and there is no 'global' statement for that name.  The
following code would treat x as global, because it is never assigned:
    def f():
        locals()['x'] = 3
        return x

Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20041109/6232202c/attachment.sig>


More information about the Python-list mailing list