Get a dictionary from an Objects Fields
Last Updated :
28 Jul, 2020
In this article, we will discuss how to get a dictionary from object’s field i.e. how to get the class members in the form of a dictionary. There are two approaches to solve the above problem:
- By using the __dict__ attribute on an object of a class and attaining the dictionary. All objects in Python have an attribute __dict__, which is a dictionary object containing all attributes defined for that object itself. The mapping of attributes with its values is done to generate a dictionary.
- By calling the in-built vars method, which is used to return __dict__ attribute of a module, class, class instance, or an object.
#Method 1: To generate a dictionary from an arbitrary object using __dict__attribute:
Python3
class Animals:
def __init__( self ):
self .lion = 'carnivore'
self .dog = 'omnivore'
self .giraffe = 'herbivore'
def printit( self ):
print ("Dictionary from the object fields\
belonging to the class Animals:")
animal = Animals()
animal.printit()
print (animal.__dict__)
|
Output:
Dictionary from the object fields belonging to the class Animals:
{‘lion’: ‘carnivore’, ‘dog’: ‘omnivore’, ‘giraffe’: ‘herbivore’}
#Method 2: To generate a dictionary from an arbitrary object using an in-built vars method:
Python3
class A:
def __init__( self ):
self .A = 1
self .B = 2
self .C = 3
self .D = 4
obj = A()
print ( vars (obj))
|
Output:
{'A': 1, 'B': 2, 'C': 3, 'D': 4}
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...