I want to have more dict’s in my init.py and I want to set its name in a variable. But it wouldn’t detect it as the name.
My Program:
JavaScript
x
7
1
from StackOverflow import *
2
3
number = input("Which car do you want:")
4
car = r"Car"+number
5
print(car["Color"])
6
print(car["Brand"])
7
StackOverflowinit.py:
JavaScript
1
10
10
1
Car1 = {
2
"Color": "Blue",
3
"Brand": "Aston Martin"
4
}
5
6
Car2 = {
7
"Color": "Red",
8
"Brand": "Volvo"
9
}
10
I expect that it give the color and brand from the chosen car. But I get this error:
JavaScript
1
5
1
Traceback (most recent call last):
2
File "D:/Users/stanw/Documents/Projecten/Stani Bot/Programma's/StackOverflow/Choose Car.py", line 5, in <module>
3
print(car["Color"])
4
TypeError: string indices must be integers
5
Advertisement
Answer
Since Python 3.7, you can use getattr
on modules.
JavaScript
1
9
1
import StackOverflow
2
3
number = input('Enter a number')
4
var_name = f'Car{number}'
5
if hasattr(StackOverflow, var_name):
6
car = getattr(StackOverflow, var_name)
7
else:
8
print('Car not found')
9