How to get a dictionary from an Object’s Fields in Python
In this article, we will look at how to get a dictionary from an object’s field in Python. When we want to get a dictionary from the object’s field, we want to get the class members. We can use one of the two methods discussed below to get the object attributes in the dictionary format.
Using __dict__
attribute:
# Declaring accuracy class class accuracy: # Init method or constructor def __init__(self): # Initializing keys with their respective values/ Instance variables self.train = 90 self.test = 60 # Defining a method to print the values def evaluation(self): print(self.train, self.test) # score object of accuracy class score = accuracy() # calling evaluation method score.evaluation() print("\r") # calling __dict__ attribute on score object and printing it print(score.__dict__)
Output:
90 60 {'train': 90, 'test': 60}
We can generate a dictionary from an arbitrary object using the __dict__ attribute. Every object in Python has __dict__ attribute. When we can call this attribute, we get the output object in a dictionary format. The resultant dictionary contains all the attributes of the object we want to inspect. The dictionary is generated via the mapping of attributes with their values. We have Initialized the instance variables as keys with their respective values inside the constructor method. Then we have defined another method to print the values. Lastly, we have created an object of the declared class and called the __dict__ attribute on that object to get the dictionary.
Using the in-built vars method in Python
# Declaring accuracy class class accuracy: # Init method or constructor def __init__(self): # Initializing keys with their respective values/ Instance variables self.train = 90 self.test = 60 # Defining a method to print the values def evaluation(self): print(self.train, self.test) # score object of accuracy class score = accuracy() # calling evaluation method score.evaluation() print("\r") # calling vars method on score object print(vars(score))
Output:
90 60 {'train': 90, 'test': 60}
We can also call the in-built the vars() method to do the same. This method is used to return the __dict__ attribute of a module, class, or object. Here, we have called the vars() method instead of the __dict__ attribute on the score object of the accuracy class.
Both the methods discussed above will return the object attributes in dictionary format. In this case, we have printed the attributes of an object that we just defined. But we can use this attribute on any object whose contents can be inspected in dictionary format.
Leave a Reply