![]() |
VOOZH | about |
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:
#Method 1: To generate a dictionary from an arbitrary object using __dict__attribute:
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:
Output:
{'A': 1, 'B': 2, 'C': 3, 'D': 4}