How to use string value as a variable name in Python?

25,792

Solution 1

I don't understand what exactly you're trying to achieve by doing this but this can be done using eval. I don't recommend using eval though. It'd be better if you tell us what you're trying to achieve finally.

>>> candy = ['a','b','c']
>>> fruit = ['d','e','f']
>>> snack = ['g','h','i']
>>> name = 'fruit'
>>> eval(name)
['d', 'e', 'f']  

EDIT

Look at the other answer by Sнаđошƒаӽ. It'll be better way to go. eval has security risk and I do not recommend its usage.

Solution 2

You can use globals() like so:

for e in globals()[name]:
    print(e)

Output:

d
e
f

And if your variables happen to be in some local scope you can use locals()

OR you can create your dictionary and access that:

d = {'candy': candy, 'fruit': fruit, 'snack': snack}
name = 'fruit'

for e in d[name]:
    print(e)

Solution 3

Use a dictionary!

my_dictionary = { #Use {} to enclose your dictionary! dictionaries are key,value pairs. so for this dict 'fruit' is a key and ['d', 'e', 'f'] are values associated with the key 'fruit'
                   'fruit' : ['d','e','f'], #indentation within a dict doesn't matter as long as each item is separated by a , 
             'candy' : ['a','b','c']           ,
                      'snack' : ['g','h','i']
    }

print my_dictionary['fruit'] # how to access a dictionary.
for key in my_dictionary:
    print key #how to iterate through a dictionary, each iteration will give you the next key
    print my_dictionary[key] #you can access the value of each key like this, it is however suggested to do the following!

for key, value in my_dictionary.iteritems():
    print key, value #where key is the key and value is the value associated with key

print my_dictionary.keys() #list of keys for a dict
print my_dictionary.values() #list of values for a dict

dictionaries by default are not ordered, and this can cause problems down the line, however there are ways around this using multidimensional arrays or orderedDicts but we will save this for a later time! I hope this helps!

Share:
25,792
Muhammad Yaseen Khan
Author by

Muhammad Yaseen Khan

Updated on August 03, 2022

Comments

  • Muhammad Yaseen Khan
    Muhammad Yaseen Khan almost 2 years

    Suppose I have lists as follows:

    candy = ['a','b','c']
    fruit = ['d','e','f']
    snack = ['g','h','i']
    

    and a string

    name = 'fruit'
    

    I want to use string name for accessing list and it's content. In this case it should be fruit. I will use name for iterating list. As:

    for x in name:
        print x