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.

Probably the easiest way to do this is to use the local variable dictionary vars() to create new variables on the fly:

food = 'bread'

vars()[food] = 123

print bread  # --> 123

You can print out vars() to see what's going on.

I tried what you have above; it seems the vars() statement in line 3 requires quotes around 'food':

vars()['food'] = 123

Otherwise works perfect.

I tried what you have above; it seems the vars() statement in line 3 requires quotes around 'food':

vars()['food'] = 123

Otherwise works perfect.

That is fine if you want to do this:

vars()['food'] = 123
print food   # --> 123

The original code wanted to print bread like this:

food = 'bread'
vars()[food] = 123
print bread  # --> 123

There is a difference there!

Now how about in methods to classes where you want to create a variable named 'self.whatever'? It works fine outside of Class methods, but I'm sure there's a way to do this. I've tried

vars()['self.test']

and

vars()[self+'.test']

. Is it possible?

Now how about in methods to classes where you want to create a variable named 'self.whatever'? It works fine outside of Class methods, but I'm sure there's a way to do this. I've tried

vars()['self.test']

and

vars()[self+'.test']

Is it possible?

class sample(object):
    def __init__(self):
        vars(self)['a'] = 10

s = sample()
print s.a
>> 10

Hope this helps.

--Karthik Jayapal

This helped me too thanks

Probably the easiest way to do this is to use the local variable dictionary vars() to create new variables on the fly:

food = 'bread'
vars()[food] = 123
print bread  # --> 123

You can print out vars() to see what's going on.

I've tried this and it works perfectly by itself but I need to use it in a method within a class and when I do this, the 'vars()[variable name] = value' line does not work and when you try to print the 'variable name', python tells you it's not defined.

i created one variable: var()[a+str(1)] = 100. so i want to call the variable name how?
how to call previously defined variables without name.
like previous resultset for "_".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.