Create a dynamic class from a dictionary
Here is i little handy trick to create a object from a dictionary or a json file
Inspiration comes from: https://stackoverflow.com/questions/1639174/creating-class-instance-properties-from-a-dictionary
First, create a class (in this example i’ve use the Car class). The init method takes a dictionary, then it populates and creates all properties for the current class (Car)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Car:
def __init__(self, dictionary):
for k, v in dictionary.items():
setattr(self, k, v)
def __repr__(self):
attrs = str([x for x in self.__dict__])
return f'<Car: {attrs}'
Here you can see how to use it. Just add a dictionry into the constructor
car_dict = {'Brand': 'Volvo', 'Model': 'X70', 'Year': 2021}
c = Car(car_dict)
print(c.Model)