2

I was just wondering if there was a way I could create variables from string like in the code below, I can create a file which includes the variable subject in the filename.

    filehandle = open('data_' + Subject + '.py', 'w')

And here I can create a new variable with the string name in the name when the file is imported.

    filehandle.write('High' + Game + 'Score = 0')

Which when I import it as a module, the variable name would be like HighMinecraftScore if Game = "Minecraft", HighMarioScore if Game = "Mario" etc.

I was just wondering if anyone knew how I accomplish the same results, as I'd hope to use it in a way in which I can create new variables with matching names autonomously.

Is there any way I can accomplish this without having to write or import modules?

Thank You

2
  • 2
    Use a dictionary or if you must, globals()[varname]=value Commented Oct 20, 2017 at 21:56
  • You can also use locals()[varname]=value for creation local variable in local symbol table or use exec("var_name = value") . Commented Jul 7, 2021 at 5:22

2 Answers 2

2

You can basically accomplish this with a dictionary. If you read the contents of the file into a dictionary with the key being the variable name and the score being the value. You've got your dynamic variables.

This is pretty much how python works behind the scenes. It uses a dictionary to store all variables and their values.

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

Comments

1

You can use a dictionary:

a_dict = {'Minecraft': 'HighMinecraftScore', 'Mario': 'HighMarioScore'}

and access them by a_dict['Minecraft'] or a_dict['Mario']

1 Comment

Don't use builtin function names as variable name (dict)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.