Get a dictionary from an Objects Fields

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:  

  1. 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.
  2. 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

filter_none

edit
close

play_arrow

link
brightness_4
code

# class Animals is declared
class Animals:
      
    # constructor
    def __init__(self):
          
        # keys are initialized with
        # their respective values
        self.lion = 'carnivore'
        self.dog = 'omnivore'
        self.giraffe = 'herbivore'
  
    def printit(self):
        print("Dictionary from the object fields\
        belonging to the class Animals:")
  
  
# object animal of class Animals
animal = Animals()
  
# calling printit method
animal.printit()
# calling attribute __dict__ on animal
# object and printing it
print(animal.__dict__)

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

# class A is declared
class A:
      
    # constructor
    def __init__(self):
          
        # keys are initialized with 
        # their respective values
        self.A = 1
        self.B = 2
        self.C = 3
        self.D = 4
  
# object obj of class A
obj = A()
  
# calling vars method on obj object
print(vars(obj))

chevron_right


Output:

{'A': 1, 'B': 2, 'C': 3, 'D': 4}

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.