locals() and dictionaries

Rocco Moretti roccomoretti at hotpop.com
Wed Feb 1 14:04:56 EST 2006


JerryB wrote:
> Hi,
> I have a dictionary, a string, and I'm creating another string, like
> this:
> 
> dict = {}
> dict[beatles] = "need"
> str = "love"
> 
> mystr = """All you %(dict[beatles])s is %(str)s""" % locals()
> 
> Why do I get
> keyerror: 'dict[one]'?
> 
> Is there a way to reference the elements in a dictionary with locals()
> or do I need to create a temp variable, like
> 
> need = dict[one]
> mystr = """All you %(need)s is %(str)s"""

1) Avoid variable names like 'dict' and 'str'- they cover up the builtin 
names.

2) When showing error, don't retype - cut and paste:

 >>> dict[beatles] = "need"

Traceback (most recent call last):
   File "<pyshell#6>", line 1, in -toplevel-
     dict[beatles] = "need"
NameError: name 'beatles' is not defined
 >>> dict['beatles'] = "need"
 >>>

3) In string formating, the item in parenthesis, used as a string, is 
the key for the dictionary. That is:

"""All you %(dict[beatles])s is %(str)s""" % ld

is the same as

"""All you %s is %s""" % (ld['dict[beatles]'],ld['str'])

4) Your best bet is not to use locals(), but to create a new dictionary 
with the appropriate keys. E.g.:

 >>> d = {}
 >>> d['beatles'] = "need"
 >>> s = "love"
 >>> d2 = d.copy()
 >>> d2['str'] = s
 >>> d['str']

Traceback (most recent call last):
   File "<pyshell#24>", line 1, in -toplevel-
     d['str']
KeyError: 'str'
 >>> d2['str']
'love'
 >>> mystr = """All you %(beatles)s is %(str)s""" % d2
 >>> print mystr
All you need is love



More information about the Python-list mailing list