Convert string to variable name in python

PythonPython 2.7

Python Problem Overview


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)?

Python Solutions


Solution 1 - Python

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

After that you can check it by:

print buffalo

As an output you will see: 2

Solution 2 - Python

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 https://stackoverflow.com/questions/11354214/creating-dynamically-named-variables-from-user-input

Solution 3 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHarshitha PalihawadanaView Question on Stackoverflow
Solution 1 - PythonStefanWView Answer on Stackoverflow
Solution 2 - PythonphntmasasinView Answer on Stackoverflow
Solution 3 - PythonDeadChexView Answer on Stackoverflow