setting a string as a variable name

Thread Solved

Join Date: Feb 2008
Posts: 1
Reputation: jopeto is an unknown quantity at this point 
Solved Threads: 0
jopeto jopeto is offline Offline
Newbie Poster

setting a string as a variable name

 
0
  #1
Feb 29th, 2008
I just started using python a couple of days ago, so I am a complete beginner. Basically what I am trying to do is the following. Imagine that I have a string variable such as:

food = 'bread'

I want to create another variable (integer or another type) so that its name is 'bread', in other words the new variable name should be the value of the string variable "food". How can I do such an assignment? My guess is that it should not take more than two or three lines. I read up and am thinking that I need to use a function called setattr, but am not able to figure out how to use it.

Thank you in advance.
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,273
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 175
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: setting a string as a variable name

 
0
  #2
Feb 29th, 2008
Probably the easiest way to do this is to use the local variable dictionary vars() to create new variables on the fly:
  1. food = 'bread'
  2.  
  3. vars()[food] = 123
  4.  
  5. print bread # --> 123
You can print out vars() to see what's going on.
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC