Python Forum

Full Version: How to convert string to variable?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,

I've had a hard time searching for this answer (Google suggests something different than I'm looking for).

VERY early in my code, I have dicts read in from a JSON file, resulting in:
  AWfromJSONfile=[1,20,300,4,5]
  AAfromJSONfile=[50,60,7,8,9]
  MAfromJSONfile=[300,400,50,60,70]

- MUCH later, I have a string variable called:
project <-- This could be either "AW", "AA", or "MA"

- For example:
project="AW" #<----(for example)

print(project + "fromJSONfile")
...how do I get the above print statement to print the contents:
1,20,300,4,5
...instead of the literal string:
"AWfromJSONfile" ?

Thanks much in advance!
CG
If fromJSONfile is a variable, You can do any of these:
print(project + str(fromJSONfile))
print("f{project}{fromJSONfile})
print(project, fromJSONfile, sep="")
If you are trying to put AW + fromJSONfile to make a variable name, and then get the value for that variable, you can do this:
varname = project+"fromJSONfile"
value = locals().get(varname)
print(value)
Or in one line:
print(locals.get(project+"fromJSONfile"))
locals() creates a dictionary of variables in the module. It would be better if you did this yourself when you read the json data so you had something like this:
jsondata ={    # Modify json so it creates a nice dictionary with keys
    "AW": [1,20,300,4,5],
    "AA": [50,60,7,8,9],
    "MA": [300,400,50,60,70]
}
print(jsondata[project]
You could do
print(globals()[project + "fromJSONfile"])
but this is not very good python, using globals() or locals() is usually frowned upon.

Instead you could define your own dictionary
fromJSONfile = {
    'AW': [1,20,300,4,5],
    'AA': [50,60,7,8,9],
    'MA': [300,400,50,60,70],}
Then
print(fromJSONfile[project])
Thank you, Dean!!

You are awesome!! I was banging my head on this for hours, and you figured out in 5 seconds! Thank you!!

In case anyone else is searching for this answer, I found I needed to make a small modification to the last example above, to get it to execute without error:
value = locals().get(project+"fromJSONfile")
Thanks again!!
CG
Wow, Gribouillis.... that is an awesome idea!!

It's going to involve some work elsewhere in the code, but I am definitely going to follow this in my next update. Thank you!!
Mandatory reading: Keep data out of your variable names and also http://stupidpythonideas.blogspot.com/20...reate.html
well, you are not creating the names in a loop, but it is basically the same problem.

Just read the JSON and use it (maybe after some transformation to dict as suggested by @Gribouillis).

btw, it's interesting to see sample of the JSON structure