473,769 Members | 2,348 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1202
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#2 4>", 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
2500
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 code: Sub Change(ByVal x, ByRef y) x = x+1 y = y+1 End Sub
2
4187
by: tedsuzman | last post by:
----- def f(): ret = 2 exec "ret += 10" return ret print f() ----- The above prints '12', as expected. However,
45
2684
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
10544
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 I am missing that feature. Maybe there is something wrong with my programming style, but I rather think it is generally useful. I fully agree with the following posting where somebody complains why so very basic and useful things are not part...
3
1499
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 PyRun_FileEx(), as you can specify dictionaries to use for the globals and locals, but it seems that you can't do the same for PyEval_CallObject() (which i use for calling the callbacks previously registered by scripts run via PyRun_FileEx()). Is there...
13
1226
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
3110
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
2968
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" that can be called during the interactive session using locals() as an argument, as follows: restart(locals()) It works. However, I would like to make this "friendlier", i.e. requiring the user to simply type
6
1786
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: def write_vars(D): """ pass D=locals() to this function... """ for key in D.keys(): exec("%s = %s" % (key,D))
0
9586
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10210
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9990
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6672
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5298
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2814
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.