Program to Form a Dictionary from an Object of a Class

Python Program to Form a Dictionary from an Object of a Class

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

Object-Oriented Programming in Python:

There are certain advantages to using object-oriented programming over alternative design patterns. Development is faster and less expensive, with improved program maintainability. As a result, the higher-quality program that is also extendable with additional methods and properties is produced. The learning curve, on the other hand, is steeper. For beginners, the notion may be too difficult. The OOPs program is slower to compute and consumes more memory since more lines of code must be written.

Object-oriented programming is built on the imperative programming paradigm, which uses statements to alter the state of a program. It is concerned with specifying how the program should work.

C, C++, Java, Go, Ruby, and Python are examples of imperative programming languages. This is in contrast to declarative programming, which focuses on what the computer program should do without stating how it should do it. Database query languages such as SQL and XQuery are examples, where one tells the machine not only what data to seek from where, but also how to do it.

Object-oriented programming (OOP) makes use of the concepts of objects and classes. A class can be viewed as a “blueprint” for things. These can each have their own set of traits (characteristics) and procedures (actions they perform).

In this post, we will look at how to get a dictionary from an object’s field, or how to retrieve the class members as a dictionary. There are two techniques to resolving the preceding problem:

By applying the __dict__ attribute to a class object and obtaining the dictionary. In Python, all objects have the attribute __dict__, which is a dictionary object holding all of the attributes defined for that object. A dictionary is created by mapping attributes to their values.
By invoking the built-in vars method, which returns the __dict__ attribute of a module, class, class instance, or object.

Program to Form a Dictionary from an Object of a Class in Python

There are two ways to create a dictionary from an object of a class in Python they are:

Method #1:Using __dict__ attribute

Approach:

  • Create a class called SamplClass.
  • In the class’s __init__ method, initialize the keys with their values and create a dictionary with the __dict__ method.
  • Print the dictionary created from the class’s object.
  • The Exit of the Program.

Below is the implementation:

# creating new class
class SamplClass:

    # default constructor which initialzes the values
    def __init__(self):

        # keys are initialized with
        # their respective values
        self.examp1 = 'hello'
        self.examp2 = 'this'
        self.examp3 = 'is'
        self.examp4 = 'btechGeeks'
    # printDict method which prints some sample text

    def printDict(self):
        print("Dictionary constructed from the object fields of the class SamplClass:")


# Creating an object to represent the class.
sampleObjec = SamplClass()

# calling printit method
sampleObjec.printDict()
# calling object __dict__ on SamplClass object and printing it
print(sampleObjec.__dict__)

Output:

Dictionary constructed from the object fields of the class SamplClass:
{'examp1': 'hello', 'examp2': 'this', 'examp3': 'is', 'examp4': 'btechGeeks'}

Explanation:

  • A class named SamplClass has been declared.
  • The keys are initialized with their values in the class’s __init__ method.
  • The dictionary is created by using the class object and the __dict__ method.
  • The dictionary constructed from the class’s object is printed.

Method #2:Using vars method

To create a dictionary from an arbitrary object, use the built-in vars method.

Approach:

  • Create a class called SamplClass.
  • In the class’s __init__ method, initialize the keys with their values and create a dictionary with the var() method.
  • Print the dictionary created from the class’s object.
  • The Exit of the Program.

Below is the implementation:

# creating new class
class SamplClass:

    # default constructor which initialzes the values
    def __init__(self):

        # keys are initialized with
        # their respective values
        self.examp1 = 'hello'
        self.examp2 = 'this'
        self.examp3 = 'is'
        self.examp4 = 'btechGeeks'
        self.examp5 = 'online'
        self.examp6 = 'coding'
        self.examp7 = 'platform'
        self.examp8 = 'for'
        self.examp9 = 'students'
    # printDict method which prints some sample text

    def printDict(self):
        print("Dictionary constructed from the object fields of the class SamplClass:")


# Creating an object to represent the class.
sampleObjec = SamplClass()

# calling printit method
sampleObjec.printDict()
# calling vars method on the object on SamplClass object and printing it
print(vars(sampleObjec))

Output:

Dictionary constructed from the object fields of the class SamplClass:
{'examp1': 'hello', 'examp2': 'this', 'examp3': 'is', 'examp4': 'btechGeeks', 'examp5': 'online', 'examp6': 'coding', 
'examp7': 'platform', 'examp8': 'for', 'examp9': 'students'}

Related Programs: