0

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).

8
  • 2
    store the operations as the object not as a string. then i will be the object instead of a string. Commented Feb 28, 2017 at 17:42
  • 4
    Use getattr(package, i). With getattr you can retrieve attributes of objects via their names as strings. Commented Feb 28, 2017 at 17:43
  • 1
    @M.O. list = [package.o1, package.o2, package.o3] Commented Feb 28, 2017 at 17:44
  • 2
    @a_guest Can you post your comment as an answer? Thanks! Commented Oct 29, 2018 at 17:51
  • 1
    @alex Done that, thanks. Commented Oct 29, 2018 at 18:14

1 Answer 1

2

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)])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.