Home > Blockchain >  How to create objects from a dict where the keys are the name objects and the values are the attribu
How to create objects from a dict where the keys are the name objects and the values are the attribu

Time:04-29

class Coche(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

CodePudding user response:

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

CodePudding user response:

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, and you can use a dict comprehension instead of a loop

my_dict = {k:Cars(*v) for k,v in dict.items()}
  • Related