How to Change a Dictionary Into a Class?
Working with Dictionary is a good thing but when we get a lot of dictionaries then it gets tough to use. So let’s understand how we can convert a dictionary into a class.
Let’s take a simple dictionary “my_dict” which has the Name, Rank, and Subject as my Keys and they have the corresponding values as Geeks, 1223, Python. We are calling a function here Dict2Class which takes our dictionary as an input and converts it to class. We then loop over our dictionary by using setattr() function to add each of the keys as attributes to the class.
setattr() is used to assign the object attribute its value. Apart from ways to assign values to class variables, through constructors and object functions, this method gives you an alternative way to assign value.
Syntax : setattr(obj, var, val)
obj : Object whose which attribute is to be assigned.
var : object attribute which has to be assigned.
val : value with which variable is to be assigned.
Below is the implementation.
, key, my_dict[key])
"After Converting Dictionary to Class : "
(result.Name, result.Rank, result.Subject)
After Converting Dictionary to Class :
Geeks 1223 Python
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses
are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!