-1

I am trying to use variables with different names while in a for loop. Before I explain anything else, let me say that this is not the problem I am having. Yes, I am creating different variables based on the index of the for loop, but I understand from that and other resources how to do that.

What I do not know how to do is how to call different variables within the for loop. What I mean is I want something sort of like this:

# pre-defined variables
object_1 = 7
object_2 = 8
object_3 = 51

# create new dictionary
Things = {}

# populate dictionary
for i in range(1,4):
    Things['thing_%d'%i] = object_i

So I know how to create separate new variables (using the dictionary Things). What I want to do is have a way that, as seen in the last line, the program identifies the variable with index i (object_i) for use in defining the element in the Things dictionary thing_i.

Is there a way to do this without having to write a separate line of code for each variable (like shown below)?

Things['thing_1'] = object_1
Things['thing_2'] = object_2
Things['thing_3'] = object_3

UPDATED EDIT AND CLARIFICATION: The reason I cannot use a dictionary to define object_1, object_2, and object_3 is they are not actually defined in the Python script. I have to call them from a Salome (3D modeling program) file where they are indexed as Face_1, Face_2, etc. I would love to have everything in elements of an array (eliminating the need for separate variables), but in order to do that, I still need to call up the objects from Salome. I currently have a script that I am running in the Salome Python console that starts out like this so I can access the objects from the Salome study:

# Salome testing
import salome
salome.salome_init("C:\Users\Me\Study3.hdf")

import GEOM
from salome.geom import geomBuilder
geompy = geomBuilder.New(salome.myStudy)

# need to retrieve all objects from that study -----------
go = salome.myStudy.FindObjectByPath("/Geometry")
it = salome.myStudy.NewChildIterator( go )
it.InitEx(True)
while it.More():
    so = it.Value()
    it.Next()
    go = so.GetObject()
    if go:
        #print(so.GetName())
        exec( "%s = go"%so.GetName() )
Community
  • 1
  • 1
  • Is unclear your question (and ambiguos) – felipsmartins Jul 16 '15 at 17:29
  • 1
    The question you linked to already explains why you should use a dictionary instead of separately-named variables. – BrenBarn Jul 16 '15 at 17:31
  • When you find yourself trying to programmatically create individually-named variables, that is a strong indication that you are [doing something wrong](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – TigerhawkT3 Jul 16 '15 at 17:32
  • @BrenBarn I understand why I should use a dictionary (therefore, as shown in the code, I am using a dictionary). My problem is calling up the different objects that were created previously in a Salome file (see edit). – Johiasburg Frowell Jul 16 '15 at 17:48
  • How do you have access to the Salome file and get vars? – Mauro Baraldi Jul 16 '15 at 21:09
  • @MauroBaraldi See the updated edit. My script is currently being loaded and ran in the Python console in Salome, although eventually I will look at how to run it without having to open the Salome GUI at all. – Johiasburg Frowell Jul 17 '15 at 13:08

5 Answers5

1

You can use the built-in method globals(), which will return a dictionary of {'object_name':object_value}, this way:

default_value = 0
for i in range(1,4):
    Things['thing_%d'%i] = globals().get('object_%d' % i, default_value)

The default_value is there in case the variable does not exists which will return default_value instead of raising KeyError exception

Iron Fist
  • 10,739
  • 2
  • 18
  • 34
1

You could loop over the values of those variables:

variables = (object_1, object_2, object_3)

Things = {}
for i, value in enumerate(variables):
    Things['thing_%d' % i] = value

At that point, you can also use a dictionary comprehension:

Things = { 'thing_%d' % i: value for i, value in enumerate(variables) }

But accessing the variables in a dynamic way, without specifying them first, is usually a bad idea and a sign for a bad design. You should change the way those variables are created in the first place then.

poke
  • 369,085
  • 72
  • 557
  • 602
1

Following is one of the way to do what you want to do

object_1 = 7
object_2 = 8
object_3 = 51

Things = {}

for i in range(1,4):
    Things['thing_%d'%i] = globals()['object_%d'%i]
Anuj
  • 994
  • 11
  • 21
  • This does not do what you think it is doing. It is creating new strings (called 'object_1', etc.) that are not related to the original variables. – Johiasburg Frowell Jul 16 '15 at 17:51
0

You can use a dictionary instead of the three different variables, with the key as object_i and the value as its value. Example -

objects = {'object_1':7,
           'object_2':8,
           'object_3':51}

Then you can access the dictionary values just as you are going to create the keys for your Things list -

for i in range(1,4):
    Things['thing_%d'%i] = objects['object_%d'%i]

The above would be one of the better solutions, but if for reason you cannot use the dictionary, you can use globals() function which returns the global namespace (of global variables) as a dictionary and then you can access your variables using strings. Example -

object_1 = 7
object_2 = 8
object_3 = 51

# create new dictionary
Things = {}
gbl = globals()
# populate dictionary
for i in range(1,4):
    Things['thing_%d'%i] = gbl['object_%d'%i]
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
0

You can also try in this way:

>>> object_1 = 7  
>>> vars()['object_1']
7
poke
  • 369,085
  • 72
  • 557
  • 602