0
class Cars(object):

    def __init__(self,brand=None,color=None,cost=None):
        self.brand = brand
        self.color = color
        self.cost = cost

imagine i have 300 cars (from car1 to car300)

dict = {"car1":["Toyota","Red",10000],
        "car2":["Tesla","White",20000],
        "car3":["Honda","Red",15000] 
       }

What I have tried:

dict1 = globals()
for k,v in dict.items():
    dict1[f"{k}"] = Cars(v[0],v[1],v[2])
    print(k,v)

Is this the best possible way to do it?

Is this an aggressive way to do it?

I wold like to learn a efficient, safe way to do it

2 Answers2

0

Use a dictionary for all the cars, not globals.

You can create it in one step with a dictionary comprehension.

all_cars = {name: Coche(brand, color, cost) for name, (brand, color, cost) in dict.items()}

print(all_cars['car1'].brand)
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Close. First, you seem to have a name problem, Cars verses Coche. And you shouldn't use dict as a variable name. And you really need to consider whether putting these variables in the global namespace is a good idea. Besides that, you should not use an F string that doesn't add anything to the variable referenced. You can unpack the list with *v and you use a dict comprehension instead of a loop

my_dict = {k:Cars(*v) for k,v in dict.items()}
tdelaney
  • 73,364
  • 6
  • 83
  • 116