0

I've a value assigned to a variable and I'm generating variable name by using loops. I wanted to assign the actual value of generated variable. If I follow the below method it is assigning string instead of value.

full_C3_sucess = 10
comp_Nonc3 = 100
for stage in ["C3", "Nonc3"]:
    for dtype in ["full", "comp"]:
        deployment = {}
        format = dtype + "_" + stage
        deployment['deployAttempted'] = format + "_sucess"

If I print deployment['deployAttempted'], it is having the string full_c3_sucess instead of it original value. Can somebody help me here.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
skys
  • 1
  • 5
    Don't use dynamic variables; use a dictionary instead; `items['full_C3_sucess']` is much easier to handle than juggling `locals()` or `globals()`. – Martijn Pieters Sep 02 '14 at 11:29

2 Answers2

0

You could:

  • use eval: print eval(deployment['deployAttempted']) but it is not a good practice.
  • use a dictionary
  • use locals() or globals()

You can find on SO similar questions. Usually, like Martijn Pieters commented, dictionary is the better choice:

mydict['full_c3_sucess'] = 10
...
print mydict[deployment['deployAttempted']]
Community
  • 1
  • 1
fredtantini
  • 15,966
  • 8
  • 49
  • 55
-1

You can use globals() and locals() to access global and local variables by name: locals()[format + "_sucess"].

wRAR
  • 25,009
  • 4
  • 84
  • 97