M.O.
M.O.

Reputation: 496

use string content as variable - python

I am using a package that has operations inside the class (? not sure what either is really), and normally the data is called this way data[package.operation]. Since I have to do multiple operations thought of shortening it and do the following

list =["o1", "o2", "o3", "o4", "o5", "o6"]
for i in list:
     print data[package.i]

but since it's considering i as a string it doesnt do the operation, and if I take away the string then it is an undefined variable. Is there a way to go around this? Or will I just have to write it the long way?.

In particular I am using pymatgen, its package Orbital and with the .operation I want to call specific suborbitals. A real example of how it would be used is data[0][Orbital.s], the first [0] denotes the element in question for which to get the orbitals s (that's why I omitted it in the code above).

Upvotes: 0

Views: 136

Answers (1)

a_guest
a_guest

Reputation: 36329

You can use getattr in order to dynamically select attributes from objects (the Orbital package in your case; for example getattr(Orbital, 's')).

So your loop would be rewritten to:

for op in ['o1', 'o2', 'o3', 'o4', 'o5', 'o6']:
    print(data[getattr(package, op)])

Upvotes: 2

Related Questions