0

I have a few pre-defined dictionaries in my python code, e.g.:

Parameter_A = {'Alpha':0.31, 'Beta':0.69}
Parameter_B = {'Alpha':0.55, 'Beta':0.75}

During execution of the python script (foo.py) I refer to the chosen parameter dictionary that I want to use (i.e. Parameter_A or Parameter_B). Like:

python foo.py A

And in the python script I have:

var = sys.argv[1]
Param = 'Parameter_' + var

The line (in script)

print 'Param = ', Param

gives output:

Param = Parameter_A

But, when I try to access the elements in the dictionary using this method,

Param['Alpha']

I get the error:

NameError: name 'Param' is not defined

I could see that in this method 'Param' (which has the string Parameter_A as its value) is of type 'str'.

But, I will really appreciate if someone can tell me how I can take 'A' or 'B' as a command line argument to indicate which one of the two dictionaries (Parameter_A or Parameter_B) my code should use.

3 Answers 3

1

Don't use eval - it's potentially dangerous (depending who supplies the arguments to your program)

you could look them up in globals()

But why not use a dict for Parameter?

Parameter = {'A': {'Alpha':0.31, 'Beta':0.69},
             'B': {'Alpha':0.55, 'Beta':0.75}}
Param = Parameter[sys.argv[1]]
Sign up to request clarification or add additional context in comments.

Comments

1

You can use eval() bif.

import sys

Parameter_A = {'Alpha':0.31, 'Beta':0.69}
Parameter_B = {'Alpha':0.55, 'Beta':0.75}

var = sys.argv[1]
Param = 'Parameter_' + var

d = eval(Param)

print(d['Alpha'])

Terminal
$ python foo.py A

Output
0.31

Comments

1

Note that Param = 'Parameter_' + var will only create a string Parameter_A not value of Parameter_A is assigned or refered anyways, on reading your code, to create something like that, you can use globals or eval.

Using globals

  var = sys.argv[1]
  Param = globals()['Parameter_' + var]  
  # here you are refering `Prameter_A` as `Param`
  print 'Param = ', Param  
  print 'Param[Alpha] = ', Param['Alpha']

Using eval

  var = sys.argv[1]
  # eval excecutes the string as python code
  # so if var is `A;import os;os.remove('somefile')`
  # will remove the file
  Param = eval('Parameter_' + var)  
  # here you are refering `Prameter_A` as `Param`
  print 'Param = ', Param  
  print 'Param[Alpha] = ', Param['Alpha']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.