473,320 Members | 1,794 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

locals() and dictionaries

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"""

Feb 1 '06 #1
4 1186
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
Feb 1 '06 #2
Rocco:
thanks for your response. The examples were just made up. I don't
normally use 'dict' and 'str'.
I know I can create a dictionary with the variables I want, etc. My
question is not how to solve the problem, or how to come up with a
work-around (I'm getting pretty good at this one :), so my question
stands:

is it possible to access the individual members of a dictionary using %
locals() when creating a string?

Thank you again for your suggestions.
Jerry

Feb 1 '06 #3
JerryB <gr******@gmail.com> wrote:
...
is it possible to access the individual members of a dictionary using %
locals() when creating a string?


Not by using the built-in locals(); you'd have to override locals to
mean someting different (not recommended).
Alex
Feb 2 '06 #4
JerryB wrote:
Rocco:
thanks for your response. The examples were just made up. I don't
normally use 'dict' and 'str'.
I know I can create a dictionary with the variables I want, etc. My
question is not how to solve the problem, or how to come up with a
work-around (I'm getting pretty good at this one :), so my question
stands:

is it possible to access the individual members of a dictionary using %
locals() when creating a string?


You might want to use a more powerful templating engine, for example
http://cheetahtemplate.org/ and probably many others.

Kent
Feb 2 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: Paul Paterson | last post by:
I am trying to find a way to mimic by-reference argument passing for immutables in Python. I need to do this because I am writing an automated VB to Python converter. Here's an example of the VB...
2
by: tedsuzman | last post by:
----- def f(): ret = 2 exec "ret += 10" return ret print f() ----- The above prints '12', as expected. However,
45
by: It's me | last post by:
I am new to the Python language. How do I do something like this: I know that a = 3 y = "a" print eval(y)
210
by: Christoph Zwerschke | last post by:
This is probably a FAQ, but I dare to ask it nevertheless since I haven't found a satisfying answer yet: Why isn't there an "ordered dictionary" class at least in the standard list? Time and again...
3
by: Faisal Alquaddoomi | last post by:
Hello, I'm having a bit of trouble isolating my scripts from each other in my embedded Python interpreter, so that their global namespaces don't get all entangled. I've had some luck with...
13
by: Lonnie Princehouse | last post by:
Can anyone think of a way to substitute a user-supplied dictionary as the local dict for a function call? e.g. def f(): x = 5 d = {}
2
by: xml0x1a | last post by:
How do I use exec? Python 2.4.3 ---- from math import * G = 1 def d(): L = 1 exec "def f(x): return L + log(G) " in globals(), locals() f(1)
2
by: =?iso-8859-1?B?QW5kcuk=?= | last post by:
I want to give a user the possibility of "restarting" an interactive session, by removing all the objects defined by her since the beginning. The way I make this possible is by having a "function"...
6
by: John [H2O] | last post by:
I would like to write a function to write variables to a file and modify a few 'counters'. This is to replace multiple instances of identical code in a module I am writing. This is my approach:...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.