1

I would like to assign the following variable names to a directory for easy manipulation later. The idea is as follow:

data_1= fits.getdata(.....)
data_2= fits.getdata(.....)
data_3= fits.getdata(.....)

. .

N=10
d={}
for i in range(N):
  d['data_'+ str(i)] = data_i

Is there a way to call the variables in a similar way?

1 Answers1

0

I have written a working solution (Please see my comments in the code for better understanding). But you have to pay attention to use the eval function in Python, it's quite dangerous.

Code:

data_1 = 1
data_2 = 2
data_3 = 3

N=10
d={}
for i in range(N):
    try:
        # IT DANGEROUS TO USE EVAL FUNCTION.
        d['data_{}'.format(i)] = eval('data_{}'.format(i))
    except NameError:
        # Cannot set the variable in the dict. Get next element of loop.
        pass

# Testing statements...
print(d["data_1"])
print(d["data_3"])
print(d["data_2"] + d["data_3"])

Output:

>>> python3 test.py 
1
3
5
milanbalazs
  • 4,811
  • 4
  • 23
  • 45