Concise idiom to initialize dictionaries
Brian Quinlan
brian at sweetapp.com
Tue Nov 9 11:50:00 EST 2004
Frohnhofer, James wrote:
> 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.
>
> First I tried:
>
> for x in (a,b,c,d,e,f,g): x = {}
>
> which didn't work (but frankly I didn't really expect it to.)
> Then I tried:
>
> for x in ('a','b','c','d','e','f','g'): locals()[x]={}
>
> which did what I wanted, in the interpreter. When I put it inside a function,
> it doesn't seem to work. If I print locals() from inside the function, I can
> see them, and they appear to be fine, but the first time I try to access one
> of them I get a "NameError: global name 'a' is not defined"
>
> Now obviously I could easily avoid this problem by just initializing each
> dictionary, but is there something wrong about my understanding of locals,
> that my function isn't behaving the way I expect?
The locals dictionary should be considered read-only. Wouldn't having a
list of dictionaries be a better strategy?
Cheers,
Brian
More information about the Python-list
mailing list