LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
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


Reply
  Search this Thread
Old 01-31-2011, 09:12 AM   #1
danubuntuman
LQ Newbie
 
Registered: Jan 2011
Location: UK
Distribution: Ubuntu 10.04 LTS
Posts: 5

Rep: Reputation: 0
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.
Old 01-31-2011, 09:48 AM   #2
Sergei Steshenko
Senior Member
 
Registered: May 2005
Posts: 4,481

Rep: Reputation: 454Reputation: 454Reputation: 454Reputation: 454Reputation: 454
Quote:
Originally Posted by danubuntuman View Post
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.
 
Old 01-31-2011, 10:31 AM   #3
Julian Andrews
LQ Newbie
 
Registered: Jan 2011
Distribution: Ubuntu
Posts: 21

Rep: Reputation: 13
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.
Old 01-31-2011, 10:36 AM   #4
danubuntuman
LQ Newbie
 
Registered: Jan 2011
Location: UK
Distribution: Ubuntu 10.04 LTS
Posts: 5

Original Poster
Rep: Reputation: 0
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!
 
Old 01-31-2011, 11:50 AM   #5
Sergei Steshenko
Senior Member
 
Registered: May 2005
Posts: 4,481

Rep: Reputation: 454Reputation: 454Reputation: 454Reputation: 454Reputation: 454
Quote:
Originally Posted by Julian Andrews View Post
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.
 
Old 01-31-2011, 01:48 PM   #6
bgeddy
Senior Member
 
Registered: Sep 2006
Location: Liverpool - England
Distribution: slackware64 13.37 and -current, Dragonfly BSD
Posts: 1,810

Rep: Reputation: 232Reputation: 232Reputation: 232
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.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Python, find unique values in a tuple or dictionary action_owl Programming 2 05-11-2010 07:16 PM
python, os.system() function. howto use python variables? jhwilliams Programming 5 07-28-2007 01:56 AM
create variables in python darkleaf Programming 7 05-28-2007 04:29 PM
Source Bash variables into Python environ. hepburnenthorpe Programming 1 05-07-2007 10:57 AM
python; retrieving dictionary of ley=value pairs passed into method TheLinuxDuck Programming 5 08-21-2003 11:56 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 02:05 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration