Concise idiom to initialize dictionaries
Bengt Richter
bokr at oz.net
Wed Nov 10 03:06:21 EST 2004
On Tue, 9 Nov 2004 16:40:48 -0000, "Frohnhofer, James" <james.frohnhofer at csfb.com> 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?
>
Others explained why locals()[x] worked interactively, and not in a function,
but if you just want a one-liner, you could just unpack a listcomp:
>>> a,b,c = [{} for i in xrange(3)]
>>> a,b,c
({}, {}, {})
If you have single-letter names, you can avoid the count by stepping through the letters:
>>> x,y,z = [{} for dont_care in 'xyz']
>>> x,y,z
({}, {}, {})
Or if you have a long target list and you can just type it and copy/paste it like:
>>> fee,fie,fo,fum,bim,bah = [{} for ignore in 'fee,fie,fo,fum,bim,bah'.split(',')]
>>> fee,fie,fo,fum,bim,bah
({}, {}, {}, {}, {}, {})
>>> map(id, (fee,fie,fo,fum,bim,bah))
[9440400, 9440976, 9438816, 9441120, 9440256, 9440544]
The dicts are separate, as you can see:
>>> id(a),id(b),id(c)
(9153392, 9153248, 9439248)
>>> a,b,c = [{i:chr(i+ord('0'))} for i in xrange(3)]
>>> a,b,c
({0: '0'}, {1: '1'}, {2: '2'})
Regards,
Bengt Richter
More information about the Python-list
mailing list