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:
#Method 1: To generate a dictionary from an arbitrary object using __dict__attribute:
Python3
# 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__)
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 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))
Output:
{'A': 1, 'B': 2, 'C': 3, 'D': 4}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4