Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I want to have more dict's in my init.py and I want to set it's name in a variable. But it wouldn't detect it as the name.

My Program:

from StackOverflow import *

number = input("Wich car do you want:")

car = r"Car"+number

print(car["Color"])

print(car["Brand"])

StackOverflow\__init__.py:

Car1 = {

    "Color": "Bleu",

    "Brand": "Aston Martin"

}

Car2 = {

    "Color": "Red",

    "Brand": "Volvo"

}

I expect that it give the color and brand from the chosen car. But I get this error:

Traceback (most recent call last):

  File "D:/Users/stanw/Documents/Projecten/Stani Bot/Programma's/StackOverflow/Choose Car.py", line 5, in <module>

    print(car["Color"])

TypeError: string indices must be integers

1 Answer

0 votes
by (25.1k points)

If you are using Python 3.7 or higher then you can use getarr on modules, like:

import StackOverflow

 

number = input('Enter a number')

var_name = f'Car{number}'

if hasattr(StackOverflow, var_name):

car = getattr(StackOverflow, var_name)

else:

    print('Car not found')

Related questions

0 votes
1 answer
0 votes
1 answer
asked Nov 28, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...