'How to create objects from a dict where the keys are the name objects and the values are the attributes? Using a loop

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



Solution 1:[1]

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)

Solution 2:[2]

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()}

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
Solution 2