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

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

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.

Jonathan
  • 8,453
  • 9
  • 51
  • 74
1

You can use a dictionary:

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

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

gommb
  • 1,121
  • 1
  • 7
  • 21