'python converting a list of strings into variable names [duplicate]
Ok so Basically I have this list. pets = ["mypets","herpets","hispets"]
and as this list was generated from reading the lines of a text file
textfile = open("pets", 'r')
lines = textfile.read()
words = lines.splitlines()
print(words)
I am now trying to find a way to convert this list from a list of strings into a list of variable names
pets = [mypets,herpets,hispets]
I would also like to point out that my issue is not in how to construct a list of variables as there may of been a missunderstanding.
Solution 1:[1]
Much better to use a dictionary as @Ynjxsjmh suggested:
all_pets = {
'mypets': ['cat','dog','snake'],
'herpets': ['bird','hamster','rabbit'],
'hispets': ['fox','bees','worms'],
}
owners = ["mypets","herpets","hispets"]
for owner in owners:
print(all_pets[owner])
Solution 2:[2]
pets = [mypets, herpets, hispets]
print(pets[0][0])
Output
cat
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | John Gordon |
| Solution 2 | inquirer |
