Skip to content
Advertisement

Global dict name in a variable

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:

from StackOverflow import *

number = input("Which car do you want:")
car = r"Car"+number
print(car["Color"])
print(car["Brand"])

StackOverflowinit.py:

Car1 = {
    "Color": "Blue",
    "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

Advertisement

Answer

Since Python 3.7, you can use getattr on modules.

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')
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement