Thursday, September 4, 2025
HomeLanguagesHow to Change a Dictionary Into a Class?

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.

Approach 

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)

Parameters :
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.

Returns :
None

Below is the implementation.

Python3




# Turns a dictionary into a class
class Dict2Class(object):
      
    def __init__(self, my_dict):
          
        for key in my_dict:
            setattr(self, key, my_dict[key])
  
# Driver Code
if __name__ == "__main__":
      
    # Creating the dictionary
    my_dict = {"Name": "Geeks",
               "Rank": "1223",
               "Subject": "Python"}
      
    result = Dict2Class(my_dict)
      
    # printing the result
    print("After Converting Dictionary to Class : ")
    print(result.Name, result.Rank, result.Subject)
    print(type(result))


Output:

After Converting Dictionary to Class : 
Geeks 1223 Python
<class '__main__.Dict2Class'>
RELATED ARTICLES

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6625 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6694 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS