Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game. |
Notices |
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
Are you new to LinuxQuestions.org? Visit the following links:
Site Howto |
Site FAQ |
Sitemap |
Register Now
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
|
 |
01-31-2011, 09:12 AM
|
#1
|
LQ Newbie
Registered: Jan 2011
Location: UK
Distribution: Ubuntu 10.04 LTS
Posts: 5
Rep:
|
Python: Create variables from dictionary keys
Hi all,
I have a situation where i need to turn a dictionary entry into a variable. I think i'm close, but am getting a syntax error (quoted at bottom)....can anyone spot whats wrong?
Code:
## Parameters.py
def dictionary_function():
p = {}
p['param_1'] = 10
p['param_2'] = 245
p['param_3'] = 18
return p
Code:
## Main.py
from parameters import dictionary_function
p = dictionary_function()
for key in p.keys():
eval(' %s=%s\n' % (key,p[key])) # turn the key into variable
I expect to be able to then type "print param_1" and get the value, however, just running the code above, I get the error:
Code:
File "<string>", line 1
param_1=10
^
SyntaxError: invalid syntax
I've tried searching for a solution, but didn't come across anything which helped me
If anyone could spot what i'm doing wrong that would be great! Many thanks!
|
|
|
Click here to see the post LQ members have rated as the most helpful post in this thread.
|
01-31-2011, 09:48 AM
|
#2
|
Senior Member
Registered: May 2005
Posts: 4,481
|
Quote:
Originally Posted by danubuntuman
Hi all,
I have a situation where i need to turn a dictionary entry into a variable. I think i'm close, but am getting a syntax error (quoted at bottom)....can anyone spot whats wrong?
Code:
## Parameters.py
def dictionary_function():
p = {}
p['param_1'] = 10
p['param_2'] = 245
p['param_3'] = 18
return p
Code:
## Main.py
from parameters import dictionary_function
p = dictionary_function()
for key in p.keys():
eval(' %s=%s\n' % (key,p[key])) # turn the key into variable
I expect to be able to then type "print param_1" and get the value, however, just running the code above, I get the error:
Code:
File "<string>", line 1
param_1=10
^
SyntaxError: invalid syntax
I've tried searching for a solution, but didn't come across anything which helped me
If anyone could spot what i'm doing wrong that would be great! Many thanks!
|
I am not a Python guy (a Perl one) ; you typically do not need what you want in the first place; if you insist, all kinds of 'eval' functions (it's its Perl name, in Python there is a number of similar functions, I don't remember their names) are your friend.
The fundamental idea is that you convert your keys into source code with variables' names derived from your keys, and then through 'eval' you compile the autogenerated code with new variables and link it (this all is "atomic", i.e. one action) with the running instance of your script.
|
|
|
01-31-2011, 10:31 AM
|
#3
|
LQ Newbie
Registered: Jan 2011
Distribution: Ubuntu
Posts: 21
Rep:
|
Hi Sergei,
I think your trouble is because you're using eval() where you should be using exec(). eval() only can evaluate expressions - not statements like an assignment. (You can think of a statement as something which would be ok in the condition for an if clause.
Code:
if param1=10: print 'yay'!
produces a syntax error.
Try the following:
Code:
for k, v in d.iteritems():
exec("%s = %s" % (k, v))
Note that using exec (or eval) can create a substantial security risk if you don't have complete control over the inputs, so it is generally discouraged if you can find another way to do what you're trying to do.
|
|
2 members found this post helpful.
|
01-31-2011, 10:36 AM
|
#4
|
LQ Newbie
Registered: Jan 2011
Location: UK
Distribution: Ubuntu 10.04 LTS
Posts: 5
Original Poster
Rep:
|
Thanks a lot for your help Julian and Sergei, Exec() did indeed work.
There shouldn't be a security risk for the application of my code really, its a simulation and just needed this to work around a problem.
Thanks for your help!
|
|
|
01-31-2011, 11:50 AM
|
#5
|
Senior Member
Registered: May 2005
Posts: 4,481
|
Quote:
Originally Posted by Julian Andrews
Hi Sergei,
I think your trouble is because you're using eval() where you should be using exec(). eval() only can evaluate expressions - not statements like an assignment. (You can think of a statement as something which would be ok in the condition for an if clause.
Code:
if param1=10: print 'yay'!
produces a syntax error.
Try the following:
Code:
for k, v in d.iteritems():
exec("%s = %s" % (k, v))
Note that using exec (or eval) can create a substantial security risk if you don't have complete control over the inputs, so it is generally discouraged if you can find another way to do what you're trying to do.
|
In Perl 'exec' is UNIX 'exec'; I have no trouble since I'm not using Python; I was talking about meaning (and explained what I meant), not about the exact names.
|
|
|
01-31-2011, 01:48 PM
|
#6
|
Senior Member
Registered: Sep 2006
Location: Liverpool - England
Distribution: slackware64 13.37 and -current, Dragonfly BSD
Posts: 1,810
|
Quote:
Note that using exec (or eval) can create a substantial security risk if you don't have complete control over the inputs, so it is generally discouraged if you can find another way to do what you're trying to do.
|
Possibly a safer way to do this when global variables are required avoiding the horrible exec:
Code:
for k, v in d.iteritems():
globals()[k]=v
or when locals variables:
Code:
for k, v in d.iteritems():
locals()[k]=v
Although still somewhat prone to security risks.
|
|
|
All times are GMT -5. The time now is 01:41 PM.
|
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.
|
Latest Threads
LQ News
|
|