say
say

Reputation: 51

How can I iterate through this list with modular variables

Let's say I have one file called colours.py that contains this:

black = (0, 0, 0)
aqua = (0, 255, 255)

And my main.py file contains:

import colours

colour_list = ['black', 'aqua']

for i in colour_list:
    colour = colours.i[0]
    print(colour)

I get AttributeError: module 'colours' has no attribute 'i'

How do I iterate through it to access the first index of each variable?

Upvotes: 0

Views: 65

Answers (2)

matszwecja
matszwecja

Reputation: 8021

i is not defined in colours module, and it will not (and should not) be replaced with the value it represents. The best way to access some values by different strings is to contain them in a dictionary.

cols = {
    "black" : (0, 0, 0),
    "aqua" : (0, 255, 255)
}


colour_list = ['black', 'aqua']

for i in colour_list:
    print(cols[i])

Ofc you can still extract the cols definition into a separate file and import it like usual.

Upvotes: 1

Xiidref
Xiidref

Reputation: 1521

You can't reference variables with the name as string like you do here (or you can, but it's using some obscure mechanism of python like reading variables from globals instead by reference).

Instead, it's better if you import the variables and use directly their references.

from colours import black, aqua

colour_list = [black, aqua]

for colour in colour_list:
    print(colour) #For the complete variable 
    print(colour[0]) #For the first index

Upvotes: 2

Related Questions