[SOLVED] Python: Create variables from dictionary keys
ProgrammingThis 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.
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.
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.
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.
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.
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.
Distribution: slackware64 13.37 and -current, Dragonfly BSD
Posts: 1,810
Rep:
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:
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.