Concise idiom to initialize dictionaries

Jeff Epler jepler at
Tue Nov 9 19:37:40 CET 2004

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

     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

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <>

More information about the Python-list mailing list