0

Say I want to do the following:

name = 1.2

The thing is that the literal name of 'name' is provided on-the-fly (it could be 'mike=1.2', 'john=1.2',...)

Hope I explained my question, and thanks in advance for any hint.

4
  • 2
    This is usually the wrong thing to do. What do you want to accomplish by this? There is almost certainly a better way. Commented May 9, 2012 at 15:56
  • Similar question posted 10 hours ago. Commented May 9, 2012 at 16:13
  • @AndrewG. at times people do ask questions because they are curious..we should provide answers to such curiosity and not be all about what should and should not be done...just saying Commented May 9, 2012 at 16:52
  • 1
    @cobie That's why "What do you want to accomplish by this?" is important. Commented May 9, 2012 at 16:58

3 Answers 3

4

Here is an example of how to do this as a dictionary.

>>> people = {}
>>> people['mike'] = 1
>>> people['john'] = 2
>>> people['mike']
1
>>> people['john']
2
>>> print people
{'mike': 1, 'john': 2}

Also see the documentation here and here

Sign up to request clarification or add additional context in comments.

Comments

3

you could do

globals()['yourvariables'] = variable

This adds the variable to the global namespace. I am not going to comment on whether it is a good idea or a bad one.

Comments

3

You can use globals() or locals() depending on the scope needed:

>>> globals()['foo'] = 'bar'
>>> foo
'bar'

If you're asking this questions, however, it means you're doing something wrong - generating variables is essentially a bad idea. You should use structures such as a dictionary for this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.