164

I have any string. like 'buffalo',

x='buffalo'

I want to convert this string to some variable name like,

buffalo=4 

not only this example, I want to convert any input string to some variable name. How should I do that (in python)?

mit
  • 11,083
  • 11
  • 50
  • 74
Harshitha Palihawadana
  • 2,171
  • 2
  • 15
  • 20

3 Answers3

182
x='buffalo'    
exec("%s = %d" % (x,2))

After that you can check it by:

print buffalo

As an output you will see: 2

StefanW
  • 1,956
  • 1
  • 11
  • 2
  • 3
    From everything I've been told. Never use exec when you can use something much safer (a dictionary), it can be dangerous. – DeadChex Oct 01 '13 at 17:44
  • 27
    Even in the very rare cases where you _do_ have a good reason to dynamically create a variable, this is not the way to do it; just use `setattr`. And even when `setattr` is inappropriate for whatever reason, being explicit and modifying `locals` or `globals` as appropriate is still better than `exec`. – abarnert Oct 01 '13 at 17:57
  • 51
    I just showed the solution that does exactly the same as OP request. – StefanW Oct 01 '13 at 17:57
  • 15
    +1 since it's what the OP wanted even though it's very unsafe and shouldn't user be used. – Nacib Neme Oct 01 '13 at 19:12
  • 21
    `exec()` is not dangerous: what is dangerous is the on how and in which context you use it. – Billal Begueradj Apr 27 '17 at 07:20
  • 10
    @BillalBEGUERADJ Thank you for adding some sense to the conversation. People always blindly freak out about exec/eval that they never understand how powerful and useful it can be when used correctly. – Dss Jun 20 '17 at 18:52
  • 1
    Can someone explain what is meant by 'dangerous' in this context? For example, I am confused if it is dangerous because it will lead to an error / crash, or if it will leak data (and if the latter, I'd be interested to know how). – Justapigeon Feb 14 '19 at 19:14
  • 2
    The problem comes when you open it up to unknown or unexpected input; because exec/eval are so powerful, a code injection can open the script up to a lot of damage. Think https://www.xkcd.com/327 but with dynamic scripts. Iff (BIG IFF) you know exactly what's going into your `exec()`, I don't see anything necessarily dangerous about using it. – jshrimp29 Nov 19 '19 at 16:02
  • 2
    @StefanW What if the 'value' is some thing else and a complex object.. (e.g `buffalo=pd.DataFrame() or {'key': 'my dict'}` etc, instead of simple integer `2`..) – Jai K Mar 16 '21 at 10:12
45

This is the best way, I know of to create dynamic variables in python.

my_dict = {}
x = "Buffalo"
my_dict[x] = 4

I found a similar, but not the same question here Creating dynamically named variables from user input

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
phntmasasin
  • 765
  • 1
  • 5
  • 14
  • 7
    You need to explain more how this solves the OPs problem, and most of all, refer to `x`, not the string literal. – Martijn Pieters Oct 01 '13 at 17:31
  • 2
    I don't get it this solution. Does my_dict["Buffalo"] prints 4? The proper answer should be print(Buffalo) should be 4 such as print(x), rather than print(my_dict["Buffalo"]). – Joonho Park Jun 01 '20 at 06:48
  • I have used this in another script. Strangely, my_dict[x] = my_dic[x] + n is working while my_dict[x] += n is not working. Why does this happen? – Joonho Park May 26 '21 at 08:50
24

You can use a Dictionary to keep track of the keys and values.

For instance...

dictOfStuff = {} ##Make a Dictionary

x = "Buffalo" ##OR it can equal the input of something, up to you.

dictOfStuff[x] = 4 ##Get the dict spot that has the same key ("name") as what X is equal to. In this case "Buffalo". and set it to 4. Or you can set it to  what ever you like

print(dictOfStuff[x]) ##print out the value of the spot in the dict that same key ("name") as the dictionary.

A dictionary is very similar to a real life dictionary. You have a word and you have a definition. You can look up the word and get the definition. So in this case, you have the word "Buffalo" and it's definition is 4. It can work with any other word and definition. Just make sure you put them into the dictionary first.

DeadChex
  • 4,379
  • 1
  • 27
  • 34