vbiqvitovs
vbiqvitovs

Reputation: 1723

Using a variable with module functions

How would I go about using a variable object to reference objects within a module or objects within a function within a module.

I am iterating through a keystring and would like to use a single character as a variable object to reference a dictionary within an imported module. I have also attempted to build a function within the module but to no luck.

Here is the code I'm working with:

...
import cipher
KeyString = 'AbCd0123'
for keystringCharacter in KeyString: 
    ReferenceList = cipher.keystringCharacter
# keystringCharacter has a value of 'A' and cipher has an object (list) of 'A' which I need to reference.

How would I go about using a variable to reference an object within this imported module?

Upvotes: 0

Views: 60

Answers (2)

chepner
chepner

Reputation: 532313

Use getattr and a list comprehension:

reference_list = [ getattr(cipher, ksc) for ksc in KeyString ]

Upvotes: 2

aIKid
aIKid

Reputation: 28322

Use getattr:

for letter in keyString:
    cipherVariables.append(getattr(cipher, letter))

The contents of cipherVariables would be something like this:

[cipher.A, cipher.b, cipher.C, ... cipher.3]

Upvotes: 3

Related Questions