Concise idiom to initialize dictionaries

Raymond Hettinger vze4rx4y at verizon.net
Tue Nov 9 19:34:18 CET 2004


[Frohnhofer, James]
> My initial problem was to initialize a bunch of dictionaries at the start of a
> function.
>
> I did not want to do
> def fn():
> a = {}
> b = {}
> c = {}
> . . .
> z = {}
> simply because it was ugly and wasted screen space.

Use exec().

>>> for c in 'abcdefghijklmnopqrstuvwxyz':
     exec c + ' = {}'


Of course, as others have pointed out, the whole idea is likely misguided and
you would be better served with a list of unnamed dictionaries.


Raymond Hettinger








More information about the Python-list mailing list